File Handling
Before you can read or write a file's contents, Java needs a way to represent where that file is and ask questions about it. That is the job of java.io.File — the classic, original class for representing a path to a file or directory on disk.
Checking Existence and Metadata
Inspecting a file with File
import java.io.File;
public class FileInfoDemo {
public static void main(String[] args) {
File file = new File("notes.txt");
System.out.println("Exists: " + file.exists());
System.out.println("Is directory: " + file.isDirectory());
System.out.println("Is file: " + file.isFile());
System.out.println("Length (bytes): " + file.length());
System.out.println("Absolute path: " + file.getAbsolutePath());
}
}Common File Methods
Method | Purpose |
|---|---|
| True if the path already exists on disk |
| True if the path is a directory |
| True if the path is a regular file |
| Size in bytes (for a file) |
| Deletes the file or empty directory, returns success as |
| Creates one directory; fails if the parent does not exist |
| Creates the directory and any missing parent directories |
| Returns the contents of a directory as a |
Creating Directories
.mkdir() vs. .mkdirs()
import java.io.File;
public class MakeDirsDemo {
public static void main(String[] args) {
File single = new File("output");
System.out.println(single.mkdir()); // works only if "." already exists
File nested = new File("output/2026/july");
System.out.println(nested.mkdirs()); // creates every missing parent too
}
}Listing Directory Contents
Listing files in a directory
import java.io.File;
public class ListFilesDemo {
public static void main(String[] args) {
File directory = new File(".");
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
String kind = entry.isDirectory() ? "[dir]" : "[file]";
System.out.println(kind + " " + entry.getName());
}
}
}
}[dir] output [file] notes.txt [file] pom.xml
Filerepresents a path and its metadata — it does not read or write content itself..exists(),.isDirectory(),.length(), and.delete()are common metadata/management operations..mkdir()creates one directory;.mkdirs()creates it plus any missing parent directories.For new code, prefer the modern
java.nio.file.Path/FilesAPI covered on the NIO page.