- 9.1. Input/Output Streams, Readers, and Writers
- 9.2. Paths, Files, and Directories
- 9.3. HTTP Connections
- 9.4. Regular Expressions
- 9.5. Serialization
- Exercises
9.2. Paths, Files, and Directories
You have already seen Path
objects for specifying file paths. In the following sections, you will see how to manipulate these objects and how to work with files and directories.
9.2.1. Paths
A Path
is a sequence of directory names, optionally followed by a file name. The first component of a path may be a root component, such as /
or C:\
. The permissible root components depend on the file system. A path that starts with a root component is absolute. Otherwise, it is relative. For example, here we construct an absolute and a relative path. For the absolute path, we assume we are running on a Unix-like file system.
Path absolute = Path.of("/", "home", "cay"); Path relative = Path.of("myapp", "conf", "user.properties");
The static Path.of
method receives one or more strings, which it joins with the path separator of the default file system (/
for a Unix-like file system, \
for Windows). It then parses the result, throwing an InvalidPathException
if the result is not a valid path in the given file system. The result is a Path
object.
You can also provide a string with separators to the Path.of
method:
Path homeDirectory = Path.of("/home/cay");
It is very common to combine or “resolve” paths. The call p.resolve(q)
returns a path according to these rules:
If
q
is absolute, then the result isq
.if
q
does not have a root, then the result is obtained by joiningp
andq
.Otherwise, the result depends on the rules of the file system.
For example, suppose your application needs to find its configuration file relative to the home directory. Here is how you can combine the paths:
Path workPath = homeDirectory.resolve("myapp/work"); // Same as homeDirectory.resolve(Path.of("myapp/work"));
There is a convenience method resolveSibling
that resolves against a path’s parent, yielding a sibling path. For example, if workPath
is /home/cay/myapp/work
, the call
Path tempPath = workPath.resolveSibling("temp");
yields /home/cay/myapp/temp
.
The opposite of resolve
is relativize
. The call p.relativize(r)
yields the path q
which, when resolved with p
, yields r
. For example,
Path.of("/home/cay").relativize(Path.of("/home/fred/myapp"))
yields ../fred/myapp
, assuming we have a file system that uses ..
to denote the parent directory.
The normalize
method removes any redundant .
and ..
components (or whatever the file system may deem redundant). For example, normalizing the path /home/cay/../fred/./myapp
yields /home/fred/myapp
.
The toAbsolutePath
method yields the absolute path of a given path. If the path is not already absolute, it is resolved against the working directory—that is, the directory of the process in which the JVM was invoked. For example, if you launched a Java program from /home/cay/myapp
, then Path.of("config").toAbsolutePath()
returns /home/cay/myapp/config
.
The Path
interface has methods for taking paths apart and combining them with other paths. This code sample shows some of the most useful ones:
Path p = Path.of("/home", "cay", "myapp.properties"); Path parent = p.getParent(); // The path/home/cay
Path file = p.getFileName(); // The last element,myapp.properties
Path root = p.getRoot(); // The initial segment/
(null
for a relative path) Path first = p.getName(0); // The first element Path dir = p.subpath(1, p.getNameCount()); // All but the first element,cay/myapp.properties
The Path
interface extends the Iterable<Path>
element, so you can iterate over the name components of a Path
with an enhanced for
loop:
for (Path component : path) { ... }
9.2.2. Creating Files and Directories
To create a new directory, call
Files.createDirectory(path);
All but the last component in the path must already exist. To create intermediate directories as well, use
Files.createDirectories(path);
You can create an empty file with
Files.createFile(path);
The call throws an exception if the file already exists. The checks for existence and the creation are atomic. If the file doesn’t exist, it is created before anyone else has a chance to do the same.
The call Files.exists(path)
checks whether the given file or directory exists. To test whether it is a directory or a “regular” file (that is, with data in it, not something like a directory or symbolic link), call the static methods isDirectory
and isRegularFile
of the Files
class.
There are convenience methods for creating a temporary file or directory in a given or system-specific location.
Path tempFile = Files.createTempFile(dir, prefix, suffix); Path tempFile = Files.createTempFile(prefix, suffix); Path tempDir = Files.createTempDirectory(dir, prefix); Path tempDir = Files.createTempDirectory(prefix);
Here, dir
is a Path
, and prefix
/suffix
are strings which may be null. For example, the call Files.createTempFile(null, ".txt")
might return a path such as /tmp/1234405522364837194.txt
.
9.2.3. Copying, Moving, and Deleting Files
To copy a file from one location to another, simply call
Files.copy(fromPath, toPath);
To move the file instead, call
Files.move(fromPath, toPath);
You can also use this command to move an empty directory.
The copy or move will fail if the target exists. If you want to overwrite an existing target, use the REPLACE_EXISTING
option. If you want to copy all file attributes, use the COPY_ATTRIBUTES
option. You can supply both like this:
Files.copy(fromPath, toPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
You can specify that a move should be atomic. Then you are assured that either the move completed successfully, or the source continues to be present. Use the ATOMIC_MOVE
option:
Files.move(fromPath, toPath, StandardCopyOption.ATOMIC_MOVE);
See Table 9.3 for a summary of the options that are available for file operations.
Finally, to delete a file, simply call
Files.delete(path);
This method throws an exception if the file doesn’t exist, so instead you may want to use
boolean deleted = Files.deleteIfExists(path);
The deletion methods can also be used to remove an empty directory.
Table 9.3: Standard Options for File Operations
Option
Description
StandardOpenOption
; use with newBufferedWriter
, newInputStream
, newOutputStream
, write
READ
Open for reading.
WRITE
Open for writing.
APPEND
If opened for writing, append to the end of the file.
TRUNCATE_EXISTING
If opened for writing, remove existing contents.
CREATE_NEW
Create a new file and fail if it exists.
CREATE
Atomically create a new file if it doesn’t exist.
DELETE_ON_CLOSE
Make a “best effort” to delete the file when it is closed.
SPARSE
A hint to the file system that this file will be sparse.
DSYNC
|SYNC
Requires that each update to the file data|data and metadata be written synchronously to the storage device.
StandardCopyOption
; use with copy
, move
ATOMIC_MOVE
Move the file atomically.
COPY_ATTRIBUTES
Copy the file attributes.
REPLACE_EXISTING
Replace the target if it exists.
LinkOption
; use with all of the above methods and exists
, isDirectory
, isRegularFile
NOFOLLOW_LINKS
Do not follow symbolic links.
FileVisitOption
; use with find
, walk
, walkFileTree
FOLLOW_LINKS
Follow symbolic links.
9.2.4. Visiting Directory Entries
The static Files.list
method returns a Stream<Path>
that reads the entries of a directory. The directory is read lazily, making it possible to efficiently process directories with huge numbers of entries.
Since reading a directory involves a system resource that needs to be closed, you should use a try-with-resources block:
try (Stream<Path> entries = Files.list(pathToDirectory)) { ... }
The list
method does not enter subdirectories. To process all descendants of a directory, use the Files.walk
method instead.
try (Stream<Path> entries = Files.walk(pathToRoot)) { // Contains all descendants, visited in depth-first order }
Here is a sample traversal of the unzipped src.zip
tree:
java java/nio java/nio/DirectCharBufferU.java java/nio/ByteBufferAsShortBufferRL.java java/nio/MappedByteBuffer.java ... java/nio/ByteBufferAsDoubleBufferB.java java/nio/charset java/nio/charset/CoderMalfunctionError.java java/nio/charset/CharsetDecoder.java java/nio/charset/UnsupportedCharsetException.java java/nio/charset/spi java/nio/charset/spi/CharsetProvider.java java/nio/charset/StandardCharsets.java java/nio/charset/Charset.java ... java/nio/charset/CoderResult.java java/nio/HeapFloatBufferR.java ...
As you can see, whenever the traversal yields a directory, it is entered before continuing with its siblings.
You can limit the depth of the tree that you want to visit by calling Files.walk(pathToRoot, depth)
. Both walk
methods have a varargs parameter of type FileVisitOption...
, but there is only one option you can supply: FOLLOW_LINKS
to follow symbolic links.
This code fragment uses the Files.walk
method to copy one directory to another:
Files.walk(source).forEach(p -> { try { Path q = target.resolve(source.relativize(p)); if (Files.isDirectory(p)) Files.createDirectory(q); else Files.copy(p, q); } catch (IOException ex) { throw new UncheckedIOException(ex); } });
Unfortunately, you cannot easily use the Files.walk
method to delete a tree of directories since you need to first visit the children before deleting the parent. In that case, use the walkFileTree
method. It requires an instance of the FileVisitor
interface. Here is when the file visitor gets notified:
Before a directory is processed:
FileVisitResult preVisitDirectory(T dir, IOException ex)
When a file is encountered:
FileVisitResult visitFile(T path, BasicFileAttributes attrs)
When an exception occurs in the
visitFile
method:FileVisitResult visitFileFailed(T path, IOException ex)
After a directory is processed:
FileVisitResult postVisitDirectory(T dir, IOException ex)
In each case, the notification method returns one of the following results:
Continue visiting the next file:
FileVisitResult.CONTINUE
Continue the walk, but without visiting the entries in this directory:
FileVisitResult.SKIP_SUBTREE
Continue the walk, but without visiting the siblings of this file:
FileVisitResult.SKIP_SIBLINGS
Terminate the walk:
FileVisitResult.TERMINATE
If any of the methods throws an exception, the walk is also terminated, and that exception is thrown from the walkFileTree
method.
The SimpleFileVisitor
class implements this interface, continuing the iteration at each point and rethrowing any exceptions.
Here is how you can delete a directory tree:
Files.walkFileTree(root, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } public FileVisitResult postVisitDirectory(Path dir, IOException ex) throws IOException { if (ex != null) throw ex; Files.delete(dir); return FileVisitResult.CONTINUE; } });
9.2.5. ZIP File Systems
The Paths
class looks up paths in the default file system—the files on the user’s local disk. You can have other file systems. One of the more useful ones is a ZIP file system. If zipname
is the name of a ZIP file, then the call
FileSystem zipfs = FileSystems.newFileSystem(Path.of(zipname));
establishes a file system that contains all files in the ZIP archive. It’s an easy matter to copy a file out of that archive if you know its name:
Files.copy(zipfs.getPath(sourceName), targetPath);
Here, zipfs.getPath
is the analog of Path.of
for an arbitrary file system.
To list all files in a ZIP archive, walk the file tree:
Files.walk(zipfs.getPath("/")).forEach(p -> { Process p });
You have to work a bit harder to create a new ZIP file. Here is the magic incantation:
Path zipPath = Path.of("myfile.zip"); var uri = URI.create("jar:" + zipPath.toUri()); // Constructs the URI jar:file://myfile.zip try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.singletonMap("create", "true"))) { // To add files, copy them into the ZIP file system Files.copy(sourcePath, zipfs.getPath("/").resolve(targetPath)); }