Java File Examples

1. Introduction

Java provides the File class as an abstraction of file and directory path names. A path is presented as a hierarchical operating system independent view of files.

The File class supports a bunch of operations on files and directories which work on both Unix-like and Windows systems. Let us look at some of these operations in more detail.

2. Creating a New File

To create a new file, use the method createNewFile(). The following creates a new file “joe” in the current directory.

File file = new File("joe");
if ( file.createNewFile() ) System.out.println("created");

If a file specified already exists, the method returns false. In this case, the existing file is not touched or modified.

2.1. Hierarchy Not Created

The method does not automatically create the directory hierarchy if any of the parent directories do not exist. The following throws an exception if directory “joe” does not exist in the current directory.

File file = new File("joe/jack");
if ( file.createNewFile() ) System.out.println("created.");

// throws: java.io.IOException: Not a directory

However, if you run the above code after creating the parent directory, it works normally.

2.2. Creating Absolute Path File

In addition to specifying relative paths as above, you can also specify an absolute path as shown below:

File file = new File("/tmp/joe");
if ( file.createNewFile() ) System.out.println("created.");

// prints "created."

2.3. Permission Denied

When attempting to create a file where you don’t have permission, you get an exception:

File file = new File("/joe");
if ( file.createNewFile() ) System.out.println("created.");

// throws java.io.IOException: Permission denied

3. Delete a File

The File class provides a delete() method to delete a file. It is used as follows:

File file = new File("joe");
if ( file.delete() ) System.out.println("deleted.");

The method does not throw an exception if the file does not exists. It just returns false.

4. List Files

When a File object is created with a directory, you can use the list() method to list the files and directories in that directory. Here is an example of listing the files in the current directory using Java 8 streams.

Arrays.stream(file.list()).forEach(System.out::println);

You can also specify a FilenameFilter to select the required files. FilenameFilter is a functional interface so let us use a lambda expression to select and print the “.class” in the directory.

File file = new File(dirPath);
Arrays
    .stream(file.list((d, f) -> f.endsWith(".class")))
    .forEach(System.out::println);

In the above example, we use the FilenameFilter for filtering files by name. However, FileFilter is another functional interface provided by java that can be used to select files by some file property. In the following example, we select empty files.

File file = new File(path);
File[] emptyFiles = Arrays
    .stream(file.listFiles(f -> f.length() == 0));

Or select hidden files for processing.

File file = new File(path);
List<File> hiddenFiles = Arrays
    .stream(file.listFiles(f -> f.isHidden()))
    .collect(Collectors.toList());

5. Creating a Directory

The File class provides the method mkdir() to create a directory. It returns false if the directory cannot be created which could be for a variety of reasons. In other words, exceptions are not thrown including for the following reasons:

  • File or directory already exists.
  • No permission.
  • Hierarchy does not exist.
File file = new File(path);
if ( file.mkdir() ) System.out.println("created.");

If you want to create all non-existent directories of the hierarchy, use mkdirs() instead.

6. Renaming a File

To rename a file, use renameTo(). You must pass in a target File object to rename the file to.

File source = new File(pathA);
File target = new File(pathB);
if ( source.renameTo(target) ) System.out.println("renamed.");

Note that this method comes with a bunch of caveats including:

  • Might not be able to move a file from one file system to another.
  • Might not work if the target path exists. (In other words, might not overwrite the target file.)
  • It might not be atomic. In other words, removing the old file and creating the new file are two separate operations in which one might fail!

With all these warnings, it is better to check the return value to be sure the operation succeeded.

Summary

The Java File class is an system independent abstraction of file and directory paths. It provides a bunch of operations to create a file, remove a file, create a directory including the hierarchy and renaming files.

Leave a Reply

Your email address will not be published. Required fields are marked *