Java File Handling

Java provides powerful APIs for creating, reading, writing, copying, moving, and deleting files and directories. The modern approach uses the java.nio.file package, especially Path and Files.

Path

Path represents the location of a file or directory. It is the main entry point for modern Java file operations.

Java
Creating and inspecting a Path.
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) {
        Path path = Path.of("data", "users.txt");

        System.out.println(path);
        System.out.println(path.getFileName());
        System.out.println(path.getParent());
    }
}

Creating a File

Files.createFile creates a new file. The operation throws an exception if the file already exists.

Java
Creating a new file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("example.txt");

        if (Files.notExists(path)) {
            Files.createFile(path);
        }

        System.out.println("File ready");
    }
}

Writing to a File

Files.writeString provides a simple way to write text into a file.

Java
Writing text to a file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("message.txt");

        Files.writeString(path, "Hello Java File API");
    }
}

Reading a File

Files.readString reads the complete contents of a text file into a String.

Java
Reading text from a file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("message.txt");

        String content = Files.readString(path);

        System.out.println(content);
    }
}

Appending to a File

StandardOpenOption.APPEND allows new content to be added instead of replacing the existing file content.

Java
Appending text to an existing file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("log.txt");

        Files.writeString(
                path,
                "New log entry\n",
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND
        );
    }
}

Checking File Properties

The Files API provides methods for checking whether a path exists and whether it represents a regular file or directory.

Java
Checking basic file properties.
Path path = Path.of("message.txt");

System.out.println(Files.exists(path));
System.out.println(Files.isRegularFile(path));
System.out.println(Files.isDirectory(path));

Copying, Moving, and Deleting

Files.copy, Files.move, and Files.delete provide common file management operations.

Java
Copying, moving, and deleting files.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path source = Path.of("source.txt");
        Path copy = Path.of("copy.txt");
        Path moved = Path.of("moved.txt");

        Files.copy(source, copy, StandardCopyOption.REPLACE_EXISTING);
        Files.move(copy, moved, StandardCopyOption.REPLACE_EXISTING);
        Files.deleteIfExists(moved);
    }
}

Creating Directories

createDirectory creates one directory, while createDirectories creates missing parent directories as necessary.

Java
Creating nested directories.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path directory = Path.of("data", "users", "profiles");

        Files.createDirectories(directory);
    }
}

Listing Directory Contents

Files.list returns a stream containing the entries directly inside a directory.

Java
Listing files in a directory.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path directory = Path.of("data");

        try (var files = Files.list(directory)) {
            files.forEach(System.out::println);
        }
    }
}

BufferedReader

BufferedReader is useful when reading text progressively, especially when processing large files line by line.

Java
Reading a file line by line.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("large-file.txt");

        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String line;

            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

BufferedWriter

BufferedWriter can be used to write text efficiently in multiple operations.

Java
Writing multiple lines with BufferedWriter.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Path.of("output.txt");

        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            writer.write("First line");
            writer.newLine();
            writer.write("Second line");
        }
    }
}

File Handling Best Practices

Prefer the java.nio.file API for modern Java applications. Use try-with-resources for streams, readers, and writers that need explicit resource management.

Check whether files or directories exist when the operation requires it, handle IOException appropriately, and avoid loading very large files completely into memory when streaming is more suitable.

File API Quick Reference

TEXT
Common Java file operations.
Path.of()             : Creates a Path
Files.exists()        : Checks existence
Files.createFile()    : Creates a file
Files.writeString()   : Writes text
Files.readString()    : Reads text
Files.copy()          : Copies a file
Files.move()          : Moves a file
Files.delete()        : Deletes a file
Files.createDirectory(): Creates a directory
Files.createDirectories(): Creates nested directories
Files.list()          : Lists directory entries

Conclusion

Java's NIO file APIs make file and directory operations straightforward and reliable. Path and Files provide the foundation for modern file handling, while buffered readers and writers are useful for processing larger amounts of text efficiently.