Course List: http://www.c-jump.com/bcc/
A package for working with directories and files
java.nio.file
The Path class provides information about the location of files and directories
A static method of the Paths class
Path get( String[, String]... )
For example,
Path filePath = Paths.get( "C:\\example\\Data.txt" );
Methods of the Path interface
Path getFileName() // name of the file or directory Path getName(int) // specific element of the path Path getName() // last element of the path int getNameCount() // how many elements present Path getParent() // for example, the parent of "/a/b/c" is "/a/b" Path getRoot() Path toAbsolutePath() // relative to absolute path File toFile() String toString // the path boolean exists() // true if path does exist boolean notExists() // true if path does not exist void delete() // deletes path, throws exception if no such path exists void deleteIfExists() // deletes path if it does exist
Determine the default file system on the host computer
FileSystem fs = FileSystems.getDefault();
Define a Path using the FileSystem.getPath() method
Path path = fs.getPath( "C:\\example\\Data.txt" );
Note: the specified path can be either absolute or relative
A relative path is a path relative to the current directory
import java.nio.file.*; public class PathDemo { public static void main(String[] args) { Path filePath = Paths.get("C:\\example\\Data.txt"); int count = filePath.getNameCount(); System.out.println("Path is " + filePath.toString()); System.out.println("File name is " + filePath.getFileName()); System.out.println("There are " + count + " elements in the file path"); for(int x = 0; x < count; ++x) System.out.println("Element " + x + " is " + filePath.getName(x)); } }
import java.util.Scanner; import java.nio.file.*; public class PathDemo2 { public static void main(String[] args) { String name; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a file name >> "); name = keyboard.nextLine(); Path inputPath = Paths.get(name); Path fullPath = inputPath.toAbsolutePath(); System.out.println("Full path is " + fullPath.toString()); } }
import java.nio.file.*; import static java.nio.file.AccessMode.*; import java.io.IOException; public class PathDemo3 { public static void main(String[] args) { Path filePath = Paths.get("C:\\example\\Data.txt"); System.out.println("Path is " + filePath.toString()); try { //READ checks that the file exists and that the program has permission to read the file //WRITE checks that the file exists and that the program has permission to write to the file //EXECUTE checks that the file exists and that the program has permission to execute the file filePath.getFileSystem().provider().checkAccess (READ, EXECUTE); System.out.println("File can be read and executed"); } catch(IOException e) { System.out.println ("File cannot be used for this application"); } } }//class PathDemo3
import java.nio.file.*; import java.io.IOException; public class PathDemo4 { public static void main(String[] args) { Path filePath = Paths.get("C:\\example\\Data.txt"); try { Files.delete(filePath); System.out.println("File or directory is deleted"); } catch (NoSuchFileException e) { System.out.println("No such file or directory"); } catch (DirectoryNotEmptyException e) { System.out.println("Directory is not empty"); } catch (SecurityException e) { System.out.println("No permission to delete"); } catch (IOException e) { System.out.println("IO exception"); } } }//class PathDemo4
import java.nio.file.attribute.*; import java.io.IOException; public class PathDemo5 { public static void main(String[] args) { Path filePath = Paths.get("C:\\example\\Data.txt"); try { BasicFileAttributes attr = Files.readAttributes(filePath, BasicFileAttributes.class); System.out.println("Creation time " + attr.creationTime()); System.out.println("Last modified time " + attr.lastModifiedTime()); System.out.println("Size " + attr.size()); } catch(IOException e) { System.out.println("IO Exception"); } } }//class PathDemo5
The time methods return a FileTime object
FileTime can be converted to a String
FileTime has the following format:
yyyy-mm-ddThh:mm:ss
four-digit year
two-digit month
two-digit day
hour : minute : seconds (separated by colons)
The seconds may include fractions of a second
FileTime values can be used in comparing the times of two files. For example,
import java.nio.file.*; import java.nio.file.attribute.*; import java.io.IOException; public class PathDemo6 { public static void main(String[] args) { Path file1 = Paths.get("C:\\example\\Data.txt"); Path file2 = Paths.get("C:\\example\\Data2.txt"); try { BasicFileAttributes attr1 = Files.readAttributes(file1, BasicFileATtributes.class); BasicFileAttributes attr2 = Files.readAttributes(file2, BasicFileAttributes.class); FileTime time1 = attr1.creationTime(); FileTime time2 = attr2.creationTime(); System.out.println("file1's creation time is: " + time1); System.out.println("file2's creation time is: " + time2); if(time1.compareTo(time2) < 0) System.out.println("file1 was created before file2"); else if(time1.compareTo(time2) > 0) System.out.println("file1 was created after file2"); else System.out.println ("file1 and file2 were created at the same time"); } catch(IOException e) { System.out.println("IO Exception"); } } }///class PathDemo6
exists(Path) notExists(Path) isReadable(Path) isWritable(Path) isDirectory(Path) isRegularFile(Path) size(Path) newDirectoryStream(Path) createFile(Path) createDirectory(Path) createDirectories(Path) delete(Path)
Code that creates a directory if it doesn't already exist
String dirString = "c:/java/files"; Path dirPath = Paths.get(dirString); if (Files.notExists(dirPath)) { Files.createDirectories(dirPath); }
Code that creates a file if it doesn't already exist
String fileString = "myfile.txt"; Path filePath = Paths.get(dirString, fileString); if (Files.notExists(filePath)) { Files.createFile(filePath); }
Code that displays information about a file
System.out.println("File name: " + filePath.getFileName()); System.out.println("Absolute path: " + filePath.toAbsolutePath()); System.out.println("Is writable: " + Files.isWritable(filePath));
Resulting output:
File name: myfile.txt Absolute path: c:\java\files\myfile.txt Is writable: true
Code that displays the files in a directory
if ( Files.exists( dirPath ) && Files.isDirectory( dirPath ) ) { System.out.println("Directory: " + dirPath.toAbsolutePath()); System.out.println("Files: "); DirectoryStream<Path> dirStream = Files.newDirectoryStream(dirPath); for (Path p: dirStream) { if (Files.isRegularFile(p)) { System.out.println(" " + p.getFileName()); } } }
Input file
Output file
I/O operations
File I/O
Stream
Output stream
Input stream
Open file
Create object
Associate stream of bytes with it
Close file
Make it no longer available to application
Should always close every file you open
Stream
Bytes flowing into program from input device
Bytes flow out of application to output device
Most streams flow in only one direction
Buffer
Memory location where bytes are held after they are logically output
But before they are sent to the output device
Using a buffer improves program performance
Flushing
Clears any bytes that have been sent to a buffer for output
But have not yet been output to a hardware device
Two types of files:
Text: contain readable characters stored as bytes and CR-LF line delimeters(*)
Binary: contain blocks of bytes used by proprietary program protocols
Two types of streams
Character
Binary
____________________
(*) The actual line delimeters are OS-specific:
CR-LF on Windows
LF on Mac OS X, UNIX, and Linux
CR on Mac OS up to version 9 and OS-9
For details, see wikipedia.org/wiki/Newline
In Java, you can obtain your local newLine delimiter as follows:
static final String newLine = System.getProperty( "line.separator" );