Home > Articles

This chapter is from the book

2.4 Working with Files

You have learned how to read and write data from a file. However, there is more to file management than reading and writing. The Path interface and Files class encapsulate the functionality required to work with the file system on the user’s machine. For example, the Files class can be used to remove or rename a file, or to find out when a file was last modified. In other words, the input/output stream classes are concerned with the contents of files, whereas the classes that we discuss here are concerned with the storage of files on a disk.

The Path interface and Files class were added in Java 7. They are much more convenient to use than the File class which dates back all the way to JDK 1.0. We expect them to be very popular with Java programmers and discuss them in depth.

2.4.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 a UNIX-like file system.

Path absolute = Paths.get("/home", "harry");
Path relative = Paths.get("myprog", "conf", "user.properties");

The static Paths.get 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.

The get method can get a single string containing multiple components. For example, you can read a path from a configuration file like this:

String baseDir = props.getProperty("base.dir");
   // May be a string such as /opt/myprog or c:\Program Files\myprog
Path basePath = Paths.get(baseDir); // OK that baseDir has separators

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 is q.

  • Otherwise, the result is “p then q,” according to the rules of the file system.

For example, suppose your application needs to find its working directory relative to a given base directory that is read from a configuration file, as in the preceding example.

Path workRelative = Paths.get("work");
Path workPath = basePath.resolve(workRelative);

There is a shortcut for the resolve method that takes a string instead of a path:

Path workPath = basePath.resolve("work");

There is a convenience method resolveSibling that resolves against a path’s parent, yielding a sibling path. For example, if workPath is /opt/myapp/work, the call

Path tempPath = workPath.resolveSibling("temp");

creates /opt/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, relativizing /home/harry against /home/fred/input.txt yields ../fred/input.txt. Here, we assume that .. denotes the parent directory in the file system.

The normalize method removes any redundant . and .. components (or whatever the file system may deem redundant). For example, normalizing the path /home/harry/../fred/./input.txt yields /home/fred/input.txt.

The toAbsolutePath method yields the absolute path of a given path, starting at a root component, such as /home/fred/input.txt or c:\Users\fred\input.txt.

The Path interface has many useful methods for taking paths apart. This code sample shows some of the most useful ones:

Path p = Paths.get("/home", "fred", "myprog.properties");
Path parent = p.getParent(); // the path /home/fred
Path file = p.getFileName(); // the path myprog.properties
Path root = p.getRoot(); // the path /

As you have already seen in Volume I, you can construct a Scanner from a Path object:

var in = new Scanner(Paths.get("/home/fred/input.txt"));

2.4.2 Reading and Writing Files

The Files class makes quick work of common file operations. For example, you can easily read the entire contents of a file:

byte[] bytes = Files.readAllBytes(path);

If you want to read the file as a string, call readAllBytes followed by

var content = new String(bytes, charset);

But if you want the file as a sequence of lines, call

List<String> lines = Files.readAllLines(path, charset);

Conversely, if you want to write a string, call

Files.write(path, content.getBytes(charset));

To append to a given file, use

Files.write(path, content.getBytes(charset), StandardOpenOption.APPEND);

You can also write a collection of lines with

Files.write(path, lines);

These simple methods are intended for dealing with text files of moderate length. If your files are large or binary, you can still use the familiar input/output streams or readers/writers:

InputStream in = Files.newInputStream(path);
OutputStream out = Files.newOutputStream(path);
Reader in = Files.newBufferedReader(path, charset);
Writer out = Files.newBufferedWriter(path, charset);

These convenience methods save you from dealing with FileInputStream, FileOutputStream, BufferedReader, or BufferedWriter.

2.4.3 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 check for existence and creation are atomic. If the file doesn’t exist, it is created before anyone else has a chance to do the same.

There are convenience methods for creating a temporary file or directory in a given or system-specific location.

Path newPath = Files.createTempFile(dir, prefix, suffix);
Path newPath = Files.createTempFile(prefix, suffix);
Path newPath = Files.createTempDirectory(dir, prefix);
Path newPath = 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.

When you create a file or directory, you can specify attributes, such as owners or permissions. However, the details depend on the file system, and we won’t cover them here.

2.4.4 Copying, Moving, and Deleting Files

To copy a file from one location to another, simply call

Files.copy(fromPath, toPath);

To move the file (that is, copy and delete the original), call

Files.move(fromPath, toPath);

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);

You can also copy an input stream to a Path, which just means saving the input stream to disk. Similarly, you can copy a Path to an output stream. Use the following calls:

Files.copy(inputStream, toPath);
Files.copy(fromPath, outputStream);

As with the other calls to copy, you can supply copy options as needed.

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.

See Table 2.3 for a summary of the options that are available for file operations.

Table 2.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 or SYNC

Requires that each update to the file data or 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

2.4.5 Getting File Information

The following static methods return a boolean value to check a property of a path:

  • exists

  • isHidden

  • isReadable, isWritable, isExecutable

  • isRegularFile, isDirectory, isSymbolicLink

The size method returns the number of bytes in a file.

long fileSize = Files.size(path);

The getOwner method returns the owner of the file, as an instance of java.nio.file.attribute.UserPrincipal.

All file systems report a set of basic attributes, encapsulated by the BasicFileAttributes interface, which partially overlaps with that information. The basic file attributes are

  • The times at which the file was created, last accessed, and last modified, as instances of the class java.nio.file.attribute.FileTime

  • Whether the file is a regular file, a directory, a symbolic link, or none of these

  • The file size

  • The file key—an object of some class, specific to the file system, that may or may not uniquely identify a file

To get these attributes, call

BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);

If you know that the user’s file system is POSIX-compliant, you can instead get an instance of PosixFileAttributes:

PosixFileAttributes attributes = Files.readAttributes(path, PosixFileAttributes.class);

Then you can find out the group owner and the owner, group, and world access permissions of the file. We won’t dwell on the details since so much of this information is not portable across operating systems.

2.4.6 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 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 delete the children before deleting the parent. The next section shows you how to overcome that problem.

2.4.7 Using Directory Streams

As you saw in the preceding section, the Files.walk method produces a Stream<Path> that traverses the descendants of a directory. Sometimes, you need more fine-grained control over the traversal process. In that case, use the Files.newDirectoryStream object instead. It yields a DirectoryStream. Note that this is not a subinterface of java.util.stream.Stream but an interface that is specialized for directory traversal. It is a subinterface of Iterable so that you can use directory stream in an enhanced for loop. Here is the usage pattern:

try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir))
{
   for (Path entry : entries)
      Process entries       
}

The try-with-resources block ensures that the directory stream is properly closed.

There is no specific order in which the directory entries are visited.

You can filter the files with a glob pattern:

try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir, "*.java"))

Table 2.4 shows all glob patterns.

Table 2.4 Glob Patterns

Pattern

Description

Example

*

Matches zero or more characters of a path component.

*.java matches all Java files in the current directory.

**

Matches zero or more characters, crossing directory boundaries.

**.java matches all Java files in any subdirectory.

?

Matches one character.

????.java matches all four-character (not counting the extension) Java files.

[. . .]

Matches a set of characters. You can use hyphens [0-9] and negation [!0-9].

Test[0-9A-F].java matches Testx.java, where x is one hexadecimal digit.

{. . .}

Matches alternatives, separated by commas.

*.{java,class} matches all Java and class files.

\

Escapes any of the above as well as \.

*\** matches all files with a * in their name.

If you want to visit all descendants of a directory, call the walkFileTree method instead and supply an object of type FileVisitor. That object gets notified

  • When a file is encountered: FileVisitResult visitFile(T path, BasicFileAttributes attrs)

  • Before a directory is processed: FileVisitResult preVisitDirectory(T dir, IOException ex)

  • After a directory is processed: FileVisitResult postVisitDirectory(T dir, IOException ex)

  • When an error occurred trying to visit a file or directory, such as trying to open a directory without the necessary permissions: FileVisitResult visitFileFailed(T path, IOException ex)

In each case, you can specify whether you want to

  • 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.

A convenience class SimpleFileVisitor implements the FileVisitor interface. All methods except visitFileFailed do nothing and continue. The visitFileFailed method throws the exception that caused the failure, thereby terminating the visit.

For example, here is how to print out all subdirectories of a given directory:

Files.walkFileTree(Paths.get("/"), new SimpleFileVisitor<Path>()
   {
      public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
            throws IOException
      {
         System.out.println(path);
         return FileVisitResult.CONTINUE;
      }      public FileVisitResult postVisitDirectory(Path dir, IOException exc)
      {
         return FileVisitResult.CONTINUE;
      }      public FileVisitResult visitFileFailed(Path path, IOException exc)
            throws IOException
      {
         return FileVisitResult.SKIP_SUBTREE;
      }
   });

Note that we need to override postVisitDirectory and visitFileFailed. Otherwise, the visit would fail as soon as it encounters a directory that it’s not allowed to open or a file it’s not allowed to access.

Also note that the attributes of the path are passed as a parameter to the preVisitDirectory and visitFile methods. The visitor already had to make an OS call to get the attributes, since it needs to distinguish between files and directories. This way, you don’t need to make another call.

The other methods of the FileVisitor interface are useful if you need to do some work when entering or leaving a directory. For example, when you delete a directory tree, you need to remove the current directory after you have removed all of its files. Here is the complete code for deleting a directory tree:

// Delete the directory tree starting at root
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 e) throws IOException
      {
         if (e != null) throw e;
         Files.delete(dir);
         return FileVisitResult.CONTINUE;
      }
   });

2.4.8 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 fs = FileSystems.newFileSystem(Paths.get(zipname), null);

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(fs.getPath(sourceName), targetPath);

Here, fs.getPath is the analog of Paths.get for an arbitrary file system.

To list all files in a ZIP archive, walk the file tree:

FileSystem fs = FileSystems.newFileSystem(Paths.get(zipname), null);
Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>()
   {
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
            throws IOException
      {               
         System.out.println(file);
         return FileVisitResult.CONTINUE;
      }
   });

That is nicer than the API described in Section 2.2.3, “ZIP Archives,” on p. 85 which required a set of new classes just to deal with ZIP archives.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020