blog

Home / DeveloperSection / Blogs / Java I/O: Accessing the Host File System

Java I/O: Accessing the Host File System

zack mathews 1399 25-May-2016

Here we discuss another important class in the I/O package. The java.io.File class provides an abstract representation of a file or directory on the host file system.

As mentioned previously, Java SE 7 introduced a new class called Path in the java.nio.file package. This class provides more sophisticated functionality than the File class. This does not, however, reduce the importance of the File class, and it is recommended that we study this class in the javadocs.  We will use the newly introduced Path class for the program in this post. Our program will accept a path on the command line and list out all the files found in the specified path.

The Directory Listing Program

The Directory Listing program accepts an argument on the command line. The program prints the names of all the files under the path specified in this argument to the system console.

Program Code

 The full program is given here:

import java.nio.file.*;
import java.io.*;

public class DirListing {
                     public static void main(String[] args) {
                             if (args.length < 1) {
                                      System.out.println("Usage: DirListing DirectoryName");                                       System.exit(0);
                             }
                             Path dirPath = Paths.get(args[0]);
                             DirectoryStream<Path> directory = null;
                             try {
                                      directory = Files.newDirectoryStream(dirPath);                                       for (Path p : directory) {
                                                System.out.println(p.getFileName());                                       }
                             } catch (Exception ie) {
                                      System.out.println("Invalid path specified:" + args[0]);                              } finally {
                                      try {
                                                if (directory != null) {
                                                          directory.close();
                                                }
                                      } catch (IOException ie) {
                                                ie.printStackTrace();
                                      }
                             }
                     }
}

 Explanation

  •  Note that at the top, we import classes from the java.nio.file package. After confirming that the user has input an argument on the command line, we construct a Path object by calling the static get method of the Paths class:

         Path dirPath = Paths.get(args[0]);

  •  After this, we declare a directory variable of type DirectoryStream, as follows(This declaration uses generics):

      DirectoryStream<Path> directory = null;

  • We initialize this variable by calling the newDirectoryStream method of the Files class on the previously created dirPath object:

       directory = Files.newDirectoryStream(dirPath);

  •  Now, we can print the names of all the files from this directory stream using a foreach loop, as follows:

for (Path p : directory) {

System.out.println(p.getFileName());

} 

 

In the finally block, we close the opened stream. We can run the program by specifying a desired path on the command line, and we will see the list of files printed to your console.

Filtering the Directory Listing

In the above example, all the files present in the specified directory are listed on the console. With a little modification to this program, we could filter out the files of a specified type in our output.

For example, we might want to list out only the files with .doc extension from the specified directory. We can add such filters easily in our program by making the following modification in the initialization of the directory object:

  • directory = dir.newDirectoryStream("*.{doc}");
  • directory = Files.newDirectoryStream(dirPath, "*.{docx}");

The newDirectoryStream method now takes a filter string as an argument. Thus, when we retrieve elements from the created stream, we get only the files with the extension .doc. We can create our own filter, as shown in the following example, which returns files having a size greater than 8,192 bytes:

DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {

         public boolean accept(Path file) throws IOException {
                                   return (Files.size(file) > 8192L);
          }
};

 To use this filter while listing the files in the directory, we would use the following code:

directory = Files.newDirectoryStream(dirPath, fil

Updated 15-Mar-2018

Leave Comment

Comments

Liked By