Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Basic I/O
I/O Streams
Byte Streams
Character Streams
Buffered Streams
Scanning and Formatting
Scanning
Formatting
I/O from the Command Line
Data Streams
Object Streams
File I/O (Featuring NIO.2)
What Is a Path? (And Other File System Facts)
The Path Class
Path Operations
File Operations
Checking a File or Directory
Deleting a File or Directory
Copying a File or Directory
Moving a File or Directory
Managing Metadata (File and File Store Attributes)
Reading, Writing, and Creating Files
Random Access Files
Creating and Reading Directories
Links, Symbolic or Otherwise
Walking the File Tree
Finding Files
Watching a Directory for Changes
Other Useful Methods
Legacy File I/O Code
Summary
Questions and Exercises
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)
Home Page >Essential Java Classes >Basic I/O
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Creating and Reading Directories

Some of the methods previously discussed, such asdelete, work on files, linksand directories. But how do you list all the directories at the top of a file system? How do you list the contents of a directory or create a directory?

This section covers the following functionality specific to directories:

Listing a File System's Root Directories

You can list all the root directories for a file system by using theFileSystem.getRootDirectories method. This method returns anIterable, which enables you to use theenhanced for statement to iterate over all the root directories.

The following code snippet prints the root directories for the default file system:

Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();for (Path name: dirs) {    System.err.println(name);}

Creating a Directory

You can create a new directory by using thecreateDirectory(Path, FileAttribute<?>) method. If you don't specify anyFileAttributes, the new directory will have default attributes. For example:

Path dir = ...;Files.createDirectory(path);

The following code snippet creates a new directory on a POSIX file system that has specific permissions:

Set<PosixFilePermission> perms =    PosixFilePermissions.fromString("rwxr-x---");FileAttribute<Set<PosixFilePermission>> attr =    PosixFilePermissions.asFileAttribute(perms);Files.createDirectory(file, attr);

To create a directory several levels deep when one or more of the parent directories might not yet exist, you can use the convenience method,createDirectories(Path, FileAttribute<?>). As with thecreateDirectory(Path, FileAttribute<?>) method, you can specify an optional set of initial file attributes. The following code snippet uses default attributes:

Files.createDirectories(Paths.get("foo/bar/test"));

The directories are created, as needed, from the top down. In thefoo/bar/test example, if thefoo directory does not exist, it is created. Next, thebar directory is created, if needed, and, finally, thetest directory is created.

It is possible for this method to fail after creating some, but not all, of the parent directories.

Creating a Temporary Directory

You can create a temporary directory using one ofcreateTempDirectory methods:

The first method allows the code to specify a location for the temporary directory and the second method creates a new directory in the default temporary-file directory.

Listing a Directory's Contents

You can list all the contents of a directory by using thenewDirectoryStream(Path) method. This method returns an object that implements theDirectoryStream interface. The class that implements theDirectoryStream interface also implementsIterable, so you can iterate through the directory stream, reading all of the objects. This approach scales well to very large directories.


Remember: The returnedDirectoryStream is astream. If you are not using atry-with-resources statement, don't forget to close the stream in thefinally block. Thetry-with-resources statement takes care of this for you.

The following code snippet shows how to print the contents of a directory:

Path dir = ...;try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {    for (Path file: stream) {        System.out.println(file.getFileName());    }} catch (IOException | DirectoryIteratorException x) {    // IOException can never be thrown by the iteration.    // In this snippet, it can only be thrown by newDirectoryStream.    System.err.println(x);}

ThePath objects returned by the iterator are the names of the entries resolved against the directory. So, if you are listing the contents of the/tmp directory, the entries are returned with the form/tmp/a,/tmp/b, and so on.

This method returns the entire contents of a directory: files, links, subdirectories, and hidden files. If you want to be more selective about the contents that are retrieved, you can use one of the othernewDirectoryStream methods, as described later in this page.

Note that if there is an exception during directory iteration thenDirectoryIteratorException is thrown with theIOException as the cause. Iterator methods cannot throw exception exceptions.

Filtering a Directory Listing By Using Globbing

If you want to fetch only files and subdirectories where each name matches a particular pattern, you can do so by using thenewDirectoryStream(Path, String) method, which provides a built-in glob filter. If you are not familiar with glob syntax, seeWhat Is a Glob?

For example, the following code snippet lists files relating to Java:.class,.java, and.jar files.:

Path dir = ...;try (DirectoryStream<Path> stream =     Files.newDirectoryStream(dir, "*.{java,class,jar}")) {    for (Path entry: stream) {        System.out.println(entry.getFileName());    }} catch (IOException x) {    // IOException can never be thrown by the iteration.    // In this snippet, it can // only be thrown by newDirectoryStream.    System.err.println(x);}

Writing Your Own Directory Filter

Perhaps you want to filter the contents of a directory based on some condition other than pattern matching. You can create your own filter by implementing theDirectoryStream.Filter<T> interface. This interface consists of one method,accept, which determines whether a file fulfills the search requirement.

For example, the following code snippet implements a filter that retrieves only directories:

DirectoryStream.Filter<Path> filter =    newDirectoryStream.Filter<Path>() {    public boolean accept(Path file) throws IOException {        try {            return (Files.isDirectory(path));        } catch (IOException x) {            // Failed to determine if it's a directory.            System.err.println(x);            return false;        }    }};

Once the filter has been created, it can be invoked by using thenewDirectoryStream(Path, DirectoryStream.Filter<? super Path>) method. The following code snippet uses theisDirectory filter to print only the directory's subdirectories to standard output:

Path dir = ...;try (DirectoryStream<Path>                       stream = Files.newDirectoryStream(dir, filter)) {    for (Path entry: stream) {        System.out.println(entry.getFileName());    }} catch (IOException x) {    System.err.println(x);}

This method is used to filter a single directory only. However, if you want to find all the subdirectories in a file tree, you would use the mechanism forWalking the File Tree.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: Random Access Files
Next page: Links, Symbolic or Otherwise

[8]ページ先頭

©2009-2025 Movatter.jp