File Class
The java.io.File class is your gateway to the file system in Java. It represents a file or directory path — not the actual data inside the file, but the path itself along with everything you can do with it: check if it exists, read its properties, create it, delete it, list its contents, and more.
Note:
Filedoes not read or write file content — it operates on the file system entry itself. For reading and writing data, pair it with streams like FileInputStream, FileReader, or the modern NIO.2 Path & Files API.
Creating a File Object
You construct a File object by passing a path string. This does not create a file on disk — it just creates a Java object pointing to that path.
import java.io.File;
public class FileExample {
public static void main(String[] args) {
File file = new File("notes.txt"); // relative path
File absFile = new File("/home/user/docs/notes.txt"); // absolute path
File fromDir = new File("/home/user/docs", "notes.txt"); // parent + child
System.out.println(file.getName()); // notes.txt
System.out.println(absFile.getParent()); // /home/user/docs
}
}
Output:
notes.txt
/home/user/docs
There are three main constructors:
| Constructor | Description |
|---|---|
File(String pathname) | Creates a File from a single path string |
File(String parent, String child) | Parent directory + child name |
File(File parent, String child) | Parent as a File object + child name |
Tip: Always use
File.separator(orFile.separatorChar) instead of hardcoding/or\, so your code runs on both Windows and Unix-based systems.
File file = new File("data" + File.separator + "report.csv");
Checking Existence and Type
Before working with a file, you typically want to verify it exists and whether it’s a file or a directory.
import java.io.File;
public class FileCheck {
public static void main(String[] args) {
File f = new File("data/config.txt");
System.out.println("Exists: " + f.exists());
System.out.println("Is file: " + f.isFile());
System.out.println("Is directory: " + f.isDirectory());
System.out.println("Is hidden: " + f.isHidden());
System.out.println("Can read: " + f.canRead());
System.out.println("Can write: " + f.canWrite());
System.out.println("Can execute: " + f.canExecute());
}
}
Output (if the file exists):
Exists: true
Is file: true
Is directory: false
Is hidden: false
Can read: true
Can write: true
Can execute: false
Getting File Properties
The File class exposes many useful metadata methods:
import java.io.File;
public class FileProperties {
public static void main(String[] args) {
File f = new File("data/report.pdf");
System.out.println("Name: " + f.getName());
System.out.println("Parent: " + f.getParent());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path: " + f.getAbsolutePath());
System.out.println("Size (bytes): " + f.length());
System.out.println("Last modified: " + f.lastModified()); // milliseconds since epoch
}
}
Output:
Name: report.pdf
Parent: data
Path: data/report.pdf
Absolute path: /home/user/project/data/report.pdf
Size (bytes): 204800
Last modified: 1718236800000
A quick reference table for the most-used property methods:
| Method | Returns |
|---|---|
getName() | Just the file/directory name (no path) |
getPath() | Path as passed to the constructor |
getAbsolutePath() | Full absolute path string |
getCanonicalPath() | Resolved path (resolves .., symlinks) — throws IOException |
getParent() | Parent directory string, or null |
length() | File size in bytes (0 for directories) |
lastModified() | Last-modified time in milliseconds since Unix epoch |
Creating Files and Directories
Creating a New File
import java.io.File;
import java.io.IOException;
public class CreateFile {
public static void main(String[] args) throws IOException {
File file = new File("output/result.txt");
boolean created = file.createNewFile();
if (created) {
System.out.println("File created: " + file.getAbsolutePath());
} else {
System.out.println("File already exists.");
}
}
}
Warning:
createNewFile()will fail with anIOExceptionif the parent directory does not exist. Always create the parent first or usemkdirs()(see below).
Creating Directories
import java.io.File;
public class CreateDir {
public static void main(String[] args) {
File dir = new File("output/reports/2024");
// mkdir() creates only one level; mkdirs() creates the full path
boolean created = dir.mkdirs();
System.out.println("Directories created: " + created);
}
}
| Method | Behaviour |
|---|---|
mkdir() | Creates a single directory — fails if parent doesn’t exist |
mkdirs() | Creates directory and any missing parent directories |
Safe Pattern: Ensure Parent Exists Before Creating a File
File file = new File("output/logs/app.log");
file.getParentFile().mkdirs(); // creates "output/logs" if needed
file.createNewFile();
Listing Directory Contents
import java.io.File;
public class ListContents {
public static void main(String[] args) {
File dir = new File("src");
// Returns an array of name strings
String[] names = dir.list();
if (names != null) {
for (String name : names) {
System.out.println(name);
}
}
System.out.println("---");
// Returns an array of File objects (more useful)
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
String type = f.isDirectory() ? "[DIR] " : "[FILE]";
System.out.println(type + " " + f.getName() + " (" + f.length() + " bytes)");
}
}
}
}
Output (example):
Main.java
utils
---
[FILE] Main.java (1024 bytes)
[DIR] utils (0 bytes)
Filtering with FilenameFilter
You can pass a lambda (or anonymous class) to filter results:
import java.io.File;
import java.io.FilenameFilter;
public class FilterFiles {
public static void main(String[] args) {
File dir = new File("src");
// List only .java files
String[] javaFiles = dir.list((d, name) -> name.endsWith(".java"));
if (javaFiles != null) {
for (String name : javaFiles) {
System.out.println(name);
}
}
}
}
Similarly, listFiles(FileFilter filter) filters by File object properties, which lets you filter on size, last-modified time, and more.
Deleting Files and Directories
import java.io.File;
public class DeleteExample {
public static void main(String[] args) {
File file = new File("temp/cache.tmp");
boolean deleted = file.delete();
System.out.println("Deleted: " + deleted);
}
}
Warning:
delete()on a directory only works if the directory is empty. To delete a non-empty directory you need to recursively delete its contents first, or use the modernFiles.walkFileTree()approach from NIO.2.
Renaming and Moving Files
renameTo() handles both renaming and moving. It returns true on success.
import java.io.File;
public class RenameExample {
public static void main(String[] args) {
File oldFile = new File("report_draft.txt");
File newFile = new File("archive/report_final.txt");
boolean success = oldFile.renameTo(newFile);
System.out.println("Renamed/moved: " + success);
}
}
Note:
renameTo()behavior can be OS-dependent — it may fail when moving across file systems. For reliable cross-platform moves, preferFiles.move()from the NIO.2 API.
Under the Hood
Internally, java.io.File stores the path as a String (the path field) and delegates every actual file-system call to native methods via java.io.FileSystem. On Linux this maps to UnixFileSystem; on Windows it maps to WinNTFileSystem. These call the underlying OS system calls (stat, mkdir, unlink, etc.) through JNI.
Key points to understand:
- A
Fileobject is just a path wrapper. Creatingnew File("notes.txt")costs almost nothing — no I/O happens until you call a method likeexists()orcreateNewFile(). getCanonicalPath()vsgetAbsolutePath()—getAbsolutePath()resolves the path relative to the current working directory but keeps..segments.getCanonicalPath()resolves symlinks and..via a real OS call, so it always returns a clean, unique path but can throwIOException.length()on directories — the return value is undefined (typically 0 or the block size). UselistFiles().lengthto count children, notlength().- NIO.2 preference — since Java 7,
java.nio.file.Pathandjava.nio.file.Filesoffer a richer, more reliable API with better error reporting, atomic operations, and file-attribute support. Usefile.toPath()to bridge between the two worlds whenever you need advanced operations.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
File f = new File("data.txt");
Path p = f.toPath(); // bridge to NIO.2
long size = Files.size(p); // more reliable than f.length()
Complete Example: Walk a Directory Tree
Here is a practical recursive method that lists every file under a directory:
import java.io.File;
public class DirectoryWalker {
public static void walk(File dir, String indent) {
File[] entries = dir.listFiles();
if (entries == null) return;
for (File entry : entries) {
System.out.println(indent + (entry.isDirectory() ? "[DIR] " : "[FILE] ") + entry.getName());
if (entry.isDirectory()) {
walk(entry, indent + " ");
}
}
}
public static void main(String[] args) {
walk(new File("src"), "");
}
}
Output (example):
[DIR] com
[DIR] example
[FILE] Main.java
[FILE] Utils.java
[FILE] module-info.java
Related Topics
- File Handling — overview of the entire file I/O landscape in Java
- Create a File — step-by-step guide to creating files safely
- Read a File Line by Line — reading file content with BufferedReader and the Files utility
- Write to a File — writing text and binary data to files
- Delete a File — safely removing files and directories
- NIO.2: Path & Files — the modern, preferred API for file-system operations in Java 7+