File Class in Java: Create, Check, List and Delete Files
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
Filecan name a file or a folder (directory). - It does not read or write file content; streams and the
Filesclass do that. Fileobjects are immutable: once created, the path they hold never changes.
2. File Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of the File Class
| Constructor | Description |
|---|---|
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
| Method | Returns | Description |
|---|---|---|
exists() | boolean | Whether the file or folder exists. |
isFile() / isDirectory() | boolean | Whether it is a normal file or a folder. |
length() | long | Size in bytes, or 0 if the file does not exist. |
createNewFile() | boolean | Creates an empty file; false if it already exists. |
mkdir() / mkdirs() | boolean | Creates one folder, or a folder with all missing parents. |
delete() | boolean | Deletes a file or an empty folder. |
renameTo(File dest) | boolean | Renames 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() | Path | Converts 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.
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());
}
}
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
- The two-argument constructor places
demo-shop-…inside the system's temporary folder, so the example does not touch your files. mkdirs()createssrcandmaintogether;mkdir()would fail becausesrcdoes not exist yet.createNewFile()returnstruethe first time andfalseonce the file exists, so you can safely call it to "create if missing".- 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.
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();
}
}
Deleting chunk-1.tmp: true Deleting chunk-2.tmp: true Remaining: [invoice.pdf, photo.jpg]
How the code works
listFiles()accepts aFileFilter; the lambda keeps only files whose names end in.tmp.- The result is checked for
null, which signals that the path is not a folder or could not be read. - Folder listings have no guaranteed order, so
Arrays.sort()sorts them, which works becauseFileimplementsComparable<File>. - Each
delete()result is printed, because a failure is reported only asfalse.
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
falseornullwithout 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; callcreateNewFile()ormkdirs(). - Ignoring boolean results. Check what
delete(),mkdirs()andrenameTo()return. - Not checking
listFiles()fornull. Looping over anullresult throwsNullPointerException. - Hard-coding separators. Use the two-argument constructor or
File.separator. - Using
Filein new code without need. PreferPathandFilesfor clearer errors.
9. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | File introduced with the core methods. |
| Java 1.2 | createNewFile(), listFiles(), createTempFile() and deleteOnExit(). |
| Java 1.6 | Disk-space methods such as getFreeSpace(). |
| Java 7 | toPath() connects File to NIO.2. |
| Java 25 | No changes to File; it remains fully supported for existing code. |
10. Summary
java.io.Filenames 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
falseornullon failure, so always check the result. delete()removes only empty folders;mkdirs()creates missing parents.- For new code, prefer
PathandFiles, and convert withtoPath().