00:00

File Class in Java: Create, Check, List and Delete Files

Last updated:

Before a program can read or write a file, it needs a way to name it: "the file report.pdf in the downloads folder". In classic Java, that job belongs to the java.io.File class. It also lets you create and delete files and folders and look up information about them.

This tutorial explains the File class, its constructors and most useful methods, two practical examples and the limitations that led to the newer Path API.

1. What Is the File Class in Java?

File represents an abstract pathname: a system-independent description of where a file or folder is. Creating a File object does not create anything on disk, and the file it names does not have to exist.

  • A File can name a file or a folder (directory).
  • It does not read or write file content; streams and the Files class do that.
  • File objects are immutable: once created, the path they hold never changes.

2. File Class Hierarchy

File class hierarchy and method groupsjava.io.File extends Object and implements Serializable and Comparable of File. Its toPath method converts it to a java.nio.file.Path, an interface added in Java 7. File methods fall into three groups: inspecting a file (exists, isFile, isDirectory, length, lastModified, getName, getParent), creating and changing it (createNewFile, mkdir, mkdirs, renameTo, delete, setReadOnly) and listing a folder (list, listFiles and listFiles with a filter).Objectextendsjava.io.Fileimplements Serializable, Comparable<File>java.nio.file.Pathinterface, Java 7toPath()Inspectexists(), isFile(), isDirectory()length(), lastModified()getName(), getParent()Create and changecreateNewFile(), mkdir()mkdirs(), renameTo()delete(), setReadOnly()List a folderlist(), listFiles()listFiles(FileFilter)listFiles(FilenameFilter)

Swipe sideways to see the whole diagram.

3. Constructors of the File Class

ConstructorDescription
File(String pathname)A file from a full or relative path, such as "notes/todo.txt".
File(String parent, String child)A file named child inside the folder parent.
File(File parent, String child)The same, with the parent given as a File.
File(URI uri)A file from a file: URI (Java 1.4).

4. Commonly Used Methods

MethodReturnsDescription
exists()booleanWhether the file or folder exists.
isFile() / isDirectory()booleanWhether it is a normal file or a folder.
length()longSize in bytes, or 0 if the file does not exist.
createNewFile()booleanCreates an empty file; false if it already exists.
mkdir() / mkdirs()booleanCreates one folder, or a folder with all missing parents.
delete()booleanDeletes a file or an empty folder.
renameTo(File dest)booleanRenames or moves the file.
list() / listFiles()String[] / File[]Contents of a folder, or null if it is not a folder or cannot be read.
toPath()PathConverts to a NIO.2 Path (Java 7).

The static fields File.separator ("/" on Linux and macOS, "\\" on Windows) and File.pathSeparator help build portable paths.

5. Example: Setting Up a Project Folder

A project generator prepares a folder structure for a new online shop: a src/main folder and an empty README.md.

ProjectFolderSetup.java
import java.io.File;
import java.io.IOException;

public class ProjectFolderSetup {
    public static void main(String[] args) throws IOException {
        File base = new File(System.getProperty("java.io.tmpdir"), "demo-shop-" + System.nanoTime());
        File srcFolder = new File(base, "src" + File.separator + "main");

        System.out.println("Folders created: " + srcFolder.mkdirs());     // creates base, src and main

        File readme = new File(base, "README.md");
        System.out.println("README created: " + readme.createNewFile());  // true: new empty file
        System.out.println("Created again:  " + readme.createNewFile());  // false: it already exists

        System.out.println("Name:   " + readme.getName());
        System.out.println("Parent: " + readme.getParentFile().equals(base));   // parent folder is base
        System.out.println("isFile: " + readme.isFile() + ", isDirectory: " + srcFolder.isDirectory());
        System.out.println("Size:   " + readme.length() + " bytes");

        // Clean up: a folder can only be deleted when it is empty
        System.out.println("Delete base first: " + base.delete());
        readme.delete();
        srcFolder.delete();
        srcFolder.getParentFile().delete();
        System.out.println("Delete base last:  " + base.delete());
    }
}
Output
Folders created: true
README created: true
Created again:  false
Name:   README.md
Parent: true
isFile: true, isDirectory: true
Size:   0 bytes
Delete base first: false
Delete base last:  true

How the code works

  1. The two-argument constructor places demo-shop-… inside the system's temporary folder, so the example does not touch your files.
  2. mkdirs() creates src and main together; mkdir() would fail because src does not exist yet.
  3. createNewFile() returns true the first time and false once the file exists, so you can safely call it to "create if missing".
  4. Deleting the base folder first fails, because delete() only removes empty folders. After its contents are removed, it succeeds.

6. Example: Cleaning Up Temporary Files

An upload service leaves partial .tmp chunks behind. This cleaner finds and deletes them while keeping real uploads.

TempFileCleaner.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class TempFileCleaner {
    public static void main(String[] args) throws IOException {
        File uploads = new File(System.getProperty("java.io.tmpdir"), "uploads-" + System.nanoTime());
        uploads.mkdir();
        for (String name : new String[] {"invoice.pdf", "photo.jpg", "chunk-1.tmp", "chunk-2.tmp"}) {
            new File(uploads, name).createNewFile();
        }

        // listFiles() with a FileFilter returns only the matching entries
        File[] leftovers = uploads.listFiles(f -> f.isFile() && f.getName().endsWith(".tmp"));
        if (leftovers == null) {                      // null means "not a folder" or an I/O error
            System.out.println("Cannot read " + uploads);
            return;
        }
        Arrays.sort(leftovers);                       // File implements Comparable<File>
        for (File f : leftovers) {
            System.out.println("Deleting " + f.getName() + ": " + f.delete());
        }

        String[] remaining = uploads.list();
        Arrays.sort(remaining);
        System.out.println("Remaining: " + Arrays.toString(remaining));

        for (File f : uploads.listFiles()) {
            f.delete();
        }
        uploads.delete();
    }
}
Output
Deleting chunk-1.tmp: true
Deleting chunk-2.tmp: true
Remaining: [invoice.pdf, photo.jpg]

How the code works

  1. listFiles() accepts a FileFilter; the lambda keeps only files whose names end in .tmp.
  2. The result is checked for null, which signals that the path is not a folder or could not be read.
  3. Folder listings have no guaranteed order, so Arrays.sort() sorts them, which works because File implements Comparable<File>.
  4. Each delete() result is printed, because a failure is reported only as false.

7. Limitations of File and When to Use Path

File has been in Java since version 1.0 and has some well-known weaknesses:

  • Most methods report failure as false or null without explaining why.
  • It cannot read or write content, copy files or handle symbolic links well.
  • Metadata such as owners and permissions is limited.

The NIO.2 Path and Files classes (Java 7) solve these problems and throw descriptive exceptions such as NoSuchFileException. File is still common in older APIs, so convert when needed with file.toPath() and path.toFile().

8. Common Mistakes and Best Practices

  • Assuming new File(...) creates a file. It only creates an object; call createNewFile() or mkdirs().
  • Ignoring boolean results. Check what delete(), mkdirs() and renameTo() return.
  • Not checking listFiles() for null. Looping over a null result throws NullPointerException.
  • Hard-coding separators. Use the two-argument constructor or File.separator.
  • Using File in new code without need. Prefer Path and Files for clearer errors.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0File introduced with the core methods.
Java 1.2createNewFile(), listFiles(), createTempFile() and deleteOnExit().
Java 1.6Disk-space methods such as getFreeSpace().
Java 7toPath() connects File to NIO.2.
Java 25No changes to File; it remains fully supported for existing code.

10. Summary

  • java.io.File names a file or folder; creating the object does not touch the disk.
  • Use it to check, create, rename, delete and list files and folders.
  • Most methods return false or null on failure, so always check the result.
  • delete() removes only empty folders; mkdirs() creates missing parents.
  • For new code, prefer Path and Files, and convert with toPath().

Related Tutorials

11. Official Java Documentation References