File Class in Java

Naveen AnamaneniUpdated · 4 min read
easyJava 25javafileslegacy

The File class in Java, in java.io, is the original way to represent a file or folder path and perform simple operations on it, such as checking whether it exists, creating folders, listing contents and deleting. It has been part of Java since version 1.0 and still appears in older code and many libraries. Its methods often report failure by returning false, which is easy to miss, so new code uses Path and Files instead. In this lesson, you will learn File so you can read and update code that uses it.

Constructors

ConstructorDescription
File(String pathname)It is used to create a File for a path.
File(String parent, String child)It joins a parent path and a child name.
File(File parent, String child)It joins a parent File and a child name.

Creating a File object doesn't create anything on disk.

Methods of File

MethodDescription
exists(), isFile(), isDirectory()It checks what the path points to.
getName(), getParent(), getPath(), getAbsolutePath()It returns parts of the path.
length()It returns the size in bytes (0 if missing).
createNewFile()It creates an empty file; returns false if it exists.
mkdir(), mkdirs()It creates one folder or the whole path; returns false on failure.
list(), listFiles()It returns the names or File objects inside a folder (null on error).
delete()It deletes a file or empty folder; returns false on failure.
renameTo(File dest)It renames or moves; returns false on failure.
lastModified()It returns the modification time in milliseconds.
toPath()It converts to a NIO.2 Path.

Example: Using File

Let's see an example of the common methods.

FileDemo.java▶ Try it
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
 
public class FileDemo {
    public static void main(String[] args) throws IOException {
        File dir = new File("classroom");
        System.out.println("mkdir: " + dir.mkdir());
        System.out.println("mkdir again: " + dir.mkdir());
 
        File a = new File(dir, "navika.txt");
        File b = new File(dir, "advitha.txt");
        System.out.println("create: " + a.createNewFile() + " "
            + b.createNewFile());
 
        String[] names = dir.list();
        Arrays.sort(names);
        System.out.println("Contents: " + Arrays.toString(names));
        System.out.println("Name: " + a.getName() + ", parent: " + a.getParent()
            + ", file? " + a.isFile());
 
        System.out.println("delete folder: " + dir.delete());
        a.delete();
        b.delete();
        System.out.println("delete folder now: " + dir.delete());
    }
}
Output
mkdir: true
mkdir again: false
create: true true
Contents: [advitha.txt, navika.txt]
Name: navika.txt, parent: classroom, file? true
delete folder: false
delete folder now: true

Explanation: mkdir returns true the first time and false when the folder already exists. list() returns names in no fixed order, so they are sorted. Deleting the folder first returns false because it isn't empty, and nothing explains why. After deleting both files, the folder can be deleted.

Moving to NIO.2

Common Mistakes

Ignoring the result of delete(), mkdir() or renameTo(). The operation may silently have failed.

Not checking listFiles() for null. It returns null if the path isn't a readable folder.

Assuming length() of a missing file throws. It returns 0.

Practice

  1. Easy: Print the name, size and last-modified time of every file in a folder using listFiles().
  2. Harder: Rewrite that program with Files.list and Files.size, and compare how errors are reported.

Quick check: File class

4 questions
1Does new File("a.txt") create a file on disk?
2What does delete() return when it can't delete?
3Which method creates all missing parent folders?
4How do you convert a File to a Path?

Key Takeaways

Was this tutorial helpful?

Lesson 361 of 482