Skip to content

Java File Handling

File handling is a core task in application development. Starting from Java 7, the java.nio.file package (NIO.2) introduced a set of modern, powerful, and easy-to-use APIs for handling files and file systems. This chapter will focus on this modern API.

Path Interface

Path is the core of the modern file API, representing the path to a file or directory. Path objects are immutable and operating system-independent.

You can create a Path object through the Paths.get() factory method.

java
import java.nio.file.Path;
import java.nio.file.Paths;

// Create a relative path
Path relativePath = Paths.get("docs", "readme.txt");

// Create an absolute path (Windows)
// Path absolutePath = Paths.get("C:\\Users\\Guest\\Documents\\report.docx");

// Create an absolute path (macOS/Linux)
// Path absolutePath = Paths.get("/home/user/documents/report.docx");

System.out.println("File name: " + relativePath.getFileName());
System.out.println("Parent directory: " + relativePath.getParent());
System.out.println("Number of path elements: " + relativePath.getNameCount());

Files Utility Class

java.nio.file.Files is a utility class containing numerous static methods for operating on files or directories represented by Path.

Checking Files/Directories

  • Files.exists(path): Checks if a file or directory exists.
  • Files.notExists(path): Checks if a file or directory does not exist.
  • Files.isDirectory(path): Checks if the path is a directory.
  • Files.isRegularFile(path): Checks if the path is a regular file.
  • Files.isReadable(path) / isWritable(path) / isExecutable(path): Checks read, write, and execute permissions of a file.
java
Path p = Paths.get("example.txt");
if (Files.exists(p)) {
    System.out.println("File exists!");
}

Creating and Deleting Files/Directories

  • Files.createFile(path): Creates a new file. Throws FileAlreadyExistsException if the file already exists.
  • Files.createDirectory(path): Creates a new directory.
  • Files.createDirectories(path): Creates a directory, including all non-existent parent directories.
  • Files.delete(path): Deletes a file or empty directory. Throws NoSuchFileException if it doesn't exist.
  • Files.deleteIfExists(path): Deletes a file or directory without throwing an error if it doesn't exist.
java
Path newDir = Paths.get("data/logs");
Path newFile = newDir.resolve("app.log"); // resolve is used to concatenate paths

try {
    Files.createDirectories(newDir);
    Files.createFile(newFile);
    System.out.println("File and directory created successfully.");
} catch (IOException e) {
    e.printStackTrace();
}

Reading and Writing Files

The Files class provides very convenient methods for reading and writing files, especially suitable for handling small files.

  • Files.writeString(path, content, options...) (Java 11+): Writes a string to a file. Creates it if it doesn't exist; overwrites content if it exists.
  • Files.readString(path) (Java 11+): Reads all content from a file and returns a string.
  • Files.write(path, bytes): Writes a byte array to a file.
  • Files.readAllBytes(path): Reads all bytes from a file.
  • Files.write(path, lines): Writes a collection of strings (lines) to a file.
  • Files.readAllLines(path): Reads all lines from a file into a List<String>.

Example (Java 11+):

java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

Path file = Paths.get("greeting.txt");

try {
    // Write to file
    String content = "Hello, Modern Java File I/O!";
    Files.writeString(file, content);
    System.out.println("Content has been written to file.");

    // Read from file
    String readContent = Files.readString(file);
    System.out.println("Content read from file:");
    System.out.println(readContent);

} catch (IOException e) {
    e.printStackTrace();
}

Copying and Moving Files

  • Files.copy(source, target, options...): Copies a file or directory.
  • Files.move(source, target, options...): Moves or renames a file or directory.

Common StandardCopyOption include:

  • REPLACE_EXISTING: Replace the target file if it already exists.
  • ATOMIC_MOVE: Ensures the move operation is atomic.
java
Path source = Paths.get("original.txt");
Path destination = Paths.get("backup/original_backup.txt");

try {
    // Ensure backup directory exists
    Files.createDirectories(destination.getParent()); 
    // Copy file, replace if target exists
    Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    e.printStackTrace();
}

For large files or scenarios requiring more fine-grained control, you can use BufferedReader, BufferedWriter, or streaming APIs, which can be combined with Files.newBufferedReader(path) and Files.newBufferedWriter(path).

Content is for learning and research only.