Chapter 14 I/O Notes Flashcards
Referencing Files and Directories
- I/O - java.io.File class
- NIO.2 - java.nio.file.Path interface.
Conceptualizing the File System
* file
* directory
* file system
* root directory
* path
* file separators
* absolute path
* relative path
* path symbol
* symbolic link
- A
file
within the storage device holds data. Files are organized into hierarchies using directories. - A
directory
is a location that can contain files as well as other directories. - The
file system
is in charge of reading and writing data within a computer. Different operating systems use different file systems to manage their data. -
root directory
is the topmost directory in the file system, ex: Windows C:\ and Linux / - A
path
is a representation of a file or directory within a file system. -
File Separators
, Unix-based systems use the forward slash, /, for paths, whereas Windows-based systems use the backslash, \ - The
absolute path
of a file or directory is the full path from the root directory to the file or directory, - the
relative path
of a file or directory is the path from the current working directory to the file or directory. - A
path symbol
is one of a reserved series of characters with special meaning in some file systems.- . A reference to the current directory
- .. A reference to the parent of the current directory
- A
symbolic link
is a special file within a file system that serves as a reference or pointer to another file or directory.
- I/O APIs do not support symbolic links,
- NIO.2 includes full support for creating, detecting, and navigating symbolic links within the file system.
I/O APIs do not support symbolic links
Operating System File Separators
Java offers a system property to retrieve the local separator character for the current environment:
System.out.print(System.getProperty(“file.separator”));
Creating a File or Path
-
I/O, this is the
java.io.File class
-
NIO.2, it is the
java.nio.file.Path interface
.
Creating a File
File zooFile1 = new File("/home/tiger/data/stripes.txt"); File zooFile2 = new File("/home/tiger", "data/stripes.txt"); File parent = new File("/home/tiger"); File zooFile3 = new File(parent, "data/stripes.txt"); System.out.println(zooFile1.exists());
The File class
is created by calling its constructor
.
This code shows three different constructors:
File zooFile1 = new File("/home/tiger/data/stripes.txt"); File zooFile2 = new File("/home/tiger", "data/stripes.txt"); File parent = new File("/home/tiger"); File zooFile3 = new File(parent, "data/stripes.txt"); System.out.println(zooFile1.exists());
All three create a File object that points to the same location on disk.
If we passed null as the parent to the final constructor, it would be ignored, and the method would behave the same way as the single String constructor.
For fun, we also show how to tell if the file exists on the file system.
Creating a Path
//Path static method of() Path zooPath1 = Path.of("/home/tiger/data/stripes.txt"); Path zooPath2 = Path.of("/home", "tiger", "data", "stripes.txt"); //Paths factory class static method get() Path zooPath3 = Paths.get("/home/tiger/data/stripes.txt"); Path zooPath4 = Paths.get("/home", "tiger", "data", "stripes.txt"); System.out.println(Files.exists(zooPath1));
- Since Path is an interface, we can’t create an instance directly. After all, interfaces don’t have constructors!
- obtain a Path object is to use a static factory method defined on Path or Paths.
All four of these examples point to the same reference on disk:
//Path static method of() Path zooPath1 = Path.of("/home/tiger/data/stripes.txt"); Path zooPath2 = Path.of("/home", "tiger", "data", "stripes.txt"); //Paths factory class static method get() Path zooPath3 = Paths.get("/home/tiger/data/stripes.txt"); Path zooPath4 = Paths.get("/home", "tiger", "data", "stripes.txt"); System.out.println(Files.exists(zooPath1));
Both methods allow passing a varargs parameter to pass additional path elements. The values are combined and automatically separated by the operating system–dependent file separator. We also show the Files helper class, which can check if the file exists on the file system.
NOTE
> [!NOTE]
both the I/O and NIO.2 classes can interact with a URI.
A uniform resource identifier (URI) is a string of characters that identifies a resource.
It begins with a schema that indicates the resource type, followed by a path value such as file:// for local file systems and http://, https://, and ftp:// for remote file systems.
- both the I/O and NIO.2 classes can interact with a URI.
- A uniform resource identifier (URI) is a string of characters that identifies a resource.
Switching between File and Path
When working with newer applications, you should rely on NIO.2’s Path interface, as it contains a lot more features.
File file = new File("rabbit"); Path nowPath = file.toPath(); File backToFile = nowPath.toFile();
Obtaining a Path from the FileSystems
Class
- The FileSystems class creates instances of the abstract FileSystem class.
- The latter includes methods for working with the file system directly.
- Both Paths.get() and Path.of() are shortcuts for this FileSystem method.
Path zooPath1 = FileSystems.getDefault().getPath("/home/tiger/data/stripes.txt"); Path zooPath2 = FileSystems.getDefault().getPath("/home", "tiger", "data", "stripes.txt");
Reviewing I/O and NIO.2 Relationships
FIGURE 14.3 I/O and NIO.2 class and interface relationships
* FileSystems create FileSystem
* FileSystem create Path
* Paths create Path
* Files uses Path
* Path covert java.net.URI
* Path covert java.io.File
NOTE
> [!NOTE]
The java.io.File is the I/O class,
while Files is an NIO.2 helper class.
Files operates on Path instances, not java.io.File instances.
- java.io.File
- java.io.nio.file.Files NIO.2 helper class
- Files operates on Path instances
TABLE 14.2 Options for creating File and Path
java.io.File
* public File(String pathname)
* public File(File parent, String child)
* public File(String parent, String child)
* public Path toPath()
java.nio.file.Path
* public default File toFile()
* public static Path of(String first, String… more)
* public static Path of(URI uri)
java.nio.file.Paths
* public static Path get(String first, String… more)
* public static Path get(URI uri)
java.nio.file.FileSystem
* public Path getPath(String first, String… more)
java.nio.file.FileSystems
* public static FileSystem getDefault()
Operating on File and Path
Answer
Using Shared Functionality
TABLE 14.3 Common File
and Path
operations
* Gets name of file/directory
* getName()
* getFileName()
* Retrieves parent directory or null if there is none
* getParent()
* getParent()
* Checks if file/directory is absolute path
* isAbsolute()
* isAbsolute()
TABLE 14.4 Common File
and Files
operations
* Deletes file/directory
* delete()
* deleteIfExists(Path p) throws IOException
* Checks if file/directory exists
* exists()
* exists(Path p, LinkOption… o)
* Retrieves absolute path of file/directory
* getAbsolutePath()
* toAbsolutePath()
* Checks if resource is directory
* isDirectory()
* isDirectory(Path p, LinkOption… o)
* Checks if resource is file
* isFile()
* isRegularFile(Path p, LinkOption… o)
* Returns the time the file was last modified
* lastModified()
* getLastModifiedTime(Path p, LinkOption… o) throws IOException
* Retrieves number of bytes in file
* length()
* size(Path p) throws IOException
* Lists contents of directory
* listFiles()
* list(Path p) throws IOException
* Creates directory
* mkdir()
* createDirectory(Path p, FileAttribute… a) throws IOException
* Creates directory including any nonexistent parent directories
* mkdirs()
* createDirectories(Path p, FileAttribute… a) throws IOException
* Renames file/directory denoted
* renameTo(File dest)
* move(Path src, Path dest, CopyOption… o) throws IOException
TABLE 14.3 Common File
and Path
operations
TABLE 14.3 Common File
and Path
operations
* Gets name of file/directory
* getName()
* getFileName()
* Retrieves parent directory or null if there is none
* getParent()
* getParent()
* Checks if file/directory is absolute path
* isAbsolute()
* isAbsolute()
TABLE 14.4 Common File
and Files
operations
TABLE 14.4 Common File
and Files
operations
* Deletes file/directory
* delete()
* deleteIfExists(Path p) throws IOException
* Checks if file/directory exists
* exists()
* exists(Path p, LinkOption… o)
* Retrieves absolute path of file/directory
* getAbsolutePath()
* toAbsolutePath() <–this is Path interface method
* Checks if resource is directory
* isDirectory()
* isDirectory(Path p, LinkOption… o)
* Checks if resource is file
* isFile()
* isRegularFile(Path p, LinkOption… o)
* Returns the time the file was last modified
* lastModified()
* getLastModifiedTime(Path p, LinkOption… o) throws IOException
* Retrieves number of bytes in file
* length()
* size(Path p) throws IOException
* Lists contents of directory
* listFiles()
* list(Path p) throws IOException
* Creates directory
* mkdir()
* createDirectory(Path p, FileAttribute… a) throws IOException
* Creates directory including any nonexistent parent directories
* mkdirs()
* createDirectories(Path p, FileAttribute… a) throws IOException
* Renames file/directory denoted
* renameTo(File dest)
* move(Path src, Path dest, CopyOption… o) throws IOException
I/O API example:
10: public static void io() { 11: var file = new File("C:\\data\\zoo.txt"); 12: if (file.exists()) { 13: System.out.println("Absolute Path: " + file.getAbsolutePath()); 14: System.out.println("Is Directory: " + file.isDirectory()); 15: System.out.println("Parent Path: " + file.getParent()); 16: if (file.isFile()) { 17: System.out.println("Size: " + file.length()); 18: System.out.println("Last Modified: " + file.lastModified()); 19: } else { 20: for (File subfile : file.listFiles()) { 21: System.out.println(" " + subfile.getName()); 22: } } } }
If the path provided points to a valid file, the program outputs something similar to the following due to the if statement on line 16:
Absolute Path: C:\data\zoo.txt Is Directory: false Parent Path: C:\data Size: 12382 Last Modified: 1650610000000
if the path provided points to a valid directory, such as C:\data, the program outputs something similar to the following, thanks to the else block:
Absolute Path: C:\data Is Directory: true Parent Path: C:\ employees.txt zoo.txt zoo-backup.txt
NOTE
> [!NOTE]
we used two backslashes (\\)
in the path String, such as C:\data\zoo.txt.
When the compiler sees a \\
inside a String expression, it interprets it as a single \
value.
compiler sees a \\
inside a String expression, it interprets it as a single \
value.
NIO.2 example:
25: public static void nio() throws IOException { 26: var path = Path.of("C:\\data\\zoo.txt"); 27: if (Files.exists(path)) { 28: System.out.println("Absolute Path: " + path.toAbsolutePath()); 29: System.out.println("Is Directory: " + Files.isDirectory(path)); 30: System.out.println("Parent Path: " + path.getParent()); 31: if (Files.isRegularFile(path)) { 32: System.out.println("Size: " + Files.size(path)); 33: System.out.println("Last Modified: " 34: + Files.getLastModifiedTime(path)); 35: } else { 36: try (Stream<Path> stream = Files.list(path)) { 37: stream.forEach(p -> 38: System.out.println(" " + p.getName())); 39: } } } }
More APIs in NIO.2 throw IOException than the I/O APIs did. In this case, Files.size(), Files.getLastModifiedTime(), and Files.list() throw an IOException.
Second, lines 36–39 use a Stream and a lambda instead of a loop. Since streams use lazy evaluation, this means the method will load each path element as needed, rather than the entire directory at once.
Closing the Stream
Stream object inside a try-with-resources?
36: try (Stream<Path> stream = Files.list(path)) { 37: stream.forEach(p -> 38: System.out.println(" " + p.getName())); 39: }
- The NIO.2 stream-based methods open a connection to the file system that must be properly closed;
- otherwise, a resource leak could ensue. A resource leak within the file system means the path may be locked from modification long after the process that used it is completed.
Handling Methods That Declare IOException
Many of the methods presented in this chapter declare IOException. Common causes of a method throwing this exception include the following:
* Loss of communication to the underlying file system.
* File or directory exists but cannot be accessed or modified.
* File exists but cannot be overwritten.
* File or directory is required but does not exist.
Methods that access or change files and directories, such as those in the Files class, often declare IOException. There are exceptions to this rule, as we will see. For example, the method Files.exists() does not declare IOException. If it did throw an exception when the file did not exist, it would never be able to return false! As a rule of thumb, if a NIO.2 method declares an IOException, it usually requires the paths it operates on to exist.
Providing NIO.2 Optional Parameters
TABLE 14.5 Common NIO.2 method arguments
-
LinkOption.NOFOLLOW_LINKS
-Do not follow symbolic links. -
StandardCopyOption.ATOMIC_MOVE
- Move file as atomic file system operation. -
StandardCopyOption.COPY_ATTRIBUTES
-Copy existing attributes to new file. -
StandardCopyOption.REPLACE_EXISTING
-Overwrite file if it already exists. -
StandardOpenOption.APPEND
-If file is already open for write, append to the end. -
StandardOpenOption.CREATE
-Create new file if it does not exist. -
StandardOpenOption.CREATE_NEW
-Create new file only if it does not exist; fail otherwise. -
StandardOpenOption.READ
-Open for read access. -
StandardOpenOption.TRUNCATE_EXISTING
-If file is already open for write, erase file and append to beginning. -
StandardOpenOption.WRITE
-Open for write access. -
FileVisitOption.FOLLOW_LINKS
-Follow symbolic links.
what the following call to Files.exists() with the LinkOption does in the following code snippet?
Path path = Paths.get("schedule.xml"); boolean exists = Files.exists(path, LinkOption.NOFOLLOW_LINKS);
- The Files.exists() simply checks whether a file exists.
- But if the parameter is a symbolic link, the method checks whether the target of the symbolic link exists, instead.
- Providing
LinkOption.NOFOLLOW_LINKS
means the default behavior will be overridden, and the method will check whether the symbolic link itself exists.