Java File

Jakob Jenkov
Last update: 2019-12-17

The Java File class, java.io.File in the Java IO API gives you access to the underlying file system. Using the Java File class you can:

This Java File tutorial will tell you more about how.

Note: The Java File class only gives you access to the file and directory meta data. If you need to read or write the content of files, you should do so using either FileInputStream, FileOutputStream or RandomAccessFile.

Note: If you are want to Java NIO (Java's non-blocking IO API) you will have to use the java.nio.FileChannel class instead. Both Java File and FileChannel works, but in case you want a pure Java NIO solution use the Java NIO FileChannel class.

Create a File

Before you can do anything with the file system or File class, you must create a Java File instance. Here is an example of creating a Java File instance:

File file = new File("c:\\data\\input-file.txt");

The Java File constructor takes as parameter the file path in the underlying file system of the file you want the File instance to point to. Note, that the file or directory path does not actually have to reference an existing file or directory. If it doesn't, you won't get an exception from the File constructor. This behaviour is useful when we want to check if a file exists, or we want to create a new file.

The Java File class also has a few other constructors you can use to instantiate File instances in different ways.

Check if File or Directory Exists

You can check if a file referenced by a Java File object exists using the File exists() method. Here is an example of checking if a file exists:

File file = new File("c:\\data\\input-file.txt");

boolean fileExists = file.exists();

The above code also works for directories. The only change you need to make to check if a directory exists is to pass a file system path to a directory to the Java File constructor, intead of a path to a file. Here is an example of checking if a directory exists:

File file = new File("c:\\data");

boolean fileExists = file.exists();

Create a Directory if it Does Not Exist

You can use the Java File class to create directories if they don't already exists. The File class contains the method mkdir() and mkdirs() for that purpose.

The mkdir() method creates a single directory if it does not already exist. Here is an example of creating a single directory via the Java File class:

File file = new File("c:\\users\\jakobjenkov\\newdir");

boolean dirCreated = file.mkdir();

Provided that the directory c:\users\jakobjenkov already exists, the above code will create a subdirectory of jakobjenkov named newdir. The mkdir() returns true if the directory was created, and false if not.

The mkdirs() will create all directories that are missing in the path the File object represents. Here is an example of creating multiple directories via the Java File class:

File file = new File("c:\\users\\jakobjenkov\\newdir");

boolean dirCreated = file.mkdirs();

Provided that the C drive exists, this example will create all the directories in the path c:\users\jakobjenkov\newdir. The mkdirs() method will return true if all the directories were created, and false if not.

File Length

The Java File class enables you to read the length in bytes of a file. To read the length of a file, call the File length() method. Here is an example of reading the length of a file via the Java File length() method:

File file = new File("c:\\data\\input-file.txt");

long length = file.length();

Rename or Move File or Directory

To rename (or move) a file, call the method renameTo() on the File class. Here is a simple example:

File file = new File("c:\\data\\input-file.txt");

boolean success = file.renameTo(new File("c:\\data\\new-file.txt"));

As briefly mentioned earlier, the renameTo() method can also be used to move a file to a different directory. The new file name passed to the renameTo() method does not have to be in the same directory as the file was already residing in.

The renameTo() method returns boolean (true or false), indicating whether the renaming was successful. Renaming of moving a file may fail for various reasons, like the file being open, wrong file permissions etc.

The Java File renameTo() method also works for directories, by the way. Just pass a path to a directory to the File constructor, instead of a path to a file.

Delete File or Directory

To delete a file call the Java File delete() method. Here is a simple example:

File file = new File("c:\\data\\input-file.txt");

boolean success = file.delete();

The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc.

The Java File delete() method also works for directories, meaning you can also delete directories with it.

Delete Directory and Subdirectories Recursively

The Java File delete() method can only delete a directory if the directory is empty. To delete a directory that contains files and subdirectories you must iterate through the directory and delete all files and subdirectories first, before you can delete the root directory. This iteration has to be carried out recursively, so you also delete all content of subdirectories and their subdirectories. Otherwise the deletion of the root directory will fail. Here is a Java method that can delete a directory and all its subdirectories and their files recursively:

public static boolean deleteDir(File dir){
    File[] files = dir.listFiles();
    if(files != null){
        for(File file : files){
            if(file.isDirectory()){
                deleteDir(file);
            } else {
                file.delete();
            }
        }
    }
    return dir.delete();
}

Check if Path is File or Directory

As mentioned several times earlier in this Java File tutorial, a File object can point to both a file or a directory. You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returns true if the File points to a directory, and false if the File points to a file. Here is a simple example:

File file = new File("c:\\data");

boolean isDirectory = file.isDirectory();

Read List of Files in Directory

You can obtain a list of all the files in a directory by calling either the Java File list() method or the listFiles() method. The list() method returns an array of String's with the file and / or directory names of directory the File object points to. The listFiles() returns an array of File objects representing the files and / or directories in the directory the File points to.

Here is an example of listing all files in a directory via the Java File list() and listFiles() methods:

File file = new File("c:\\data");

String[] fileNames = file.list();

File[]   files = file.listFiles();

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next