File Handling in Java

Naveen AnamaneniUpdated · 4 min read

File handling in Java means working with files and folders on disk: creating them, writing data to them, reading data from them, and copying, moving, renaming and deleting them. Java has two APIs for this. The older java.io.File class has existed since Java 1.0. The modern NIO.2 API, added in Java 7 in the java.nio.file package, uses the Path interface and the Files class and is the recommended choice today. In this lesson, you will get an overview of both and a first complete example.

The Two APIs

java.io.File (legacy)NIO.2: Path and Files (modern)
Added inJava 1.0Java 7
Represents a location withFilePath
Operations live inMethods of FileStatic methods of Files
ErrorsMany methods just return falseMethods throw descriptive exceptions
Reading and writing textNeeds streamsFiles.readString, Files.writeString in one line
Walking folder treesWrite your own recursionFiles.walk, Files.find
Symbolic links, permissions, attributesLimitedFull support

Common File Operations at a Glance

TaskNIO.2 method
Point to a filePath.of("data", "marks.txt")
Create a fileFiles.createFile(path)
Write textFiles.writeString(path, text)
Read textFiles.readString(path)
Read linesFiles.readAllLines(path), Files.lines(path)
Check existenceFiles.exists(path)
Copy, move, deleteFiles.copy, Files.move, Files.delete
Create foldersFiles.createDirectories(path)
List or walk a folderFiles.list(dir), Files.walk(dir)

Example: A Complete Round Trip

Let's see an example that creates a folder, writes a file, reads it, copies it and cleans up.

RoundTrip.java▶ Try it
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
 
public class RoundTrip {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createDirectories(Path.of("school"));
        Path file = dir.resolve("students.txt");
 
        Files.write(file, List.of("Navika", "Srihitha", "Advitha"));
        System.out.println("Exists: " + Files.exists(file)
            + ", size: " + Files.size(file) + " bytes");
 
        List<String> names = Files.readAllLines(file);
        System.out.println("Read: " + names);
 
        Path backup = Files.copy(file, dir.resolve("students.bak"));
        System.out.println("Backup: " + backup);
 
        Files.delete(backup);
        Files.delete(file);
        Files.delete(dir);
        System.out.println("Cleaned up: " + Files.notExists(dir));
    }
}
Output
Exists: true, size: 24 bytes
Read: [Navika, Srihitha, Advitha]
Backup: school/students.bak
Cleaned up: true

Explanation: Path.of("school") describes a location; Files.createDirectories creates the folder. resolve builds a path inside it. Files.write writes each name on its own line (6 + 8 + 7 letters plus 3 line breaks = 24 bytes), and readAllLines reads them back. Every operation is a single static call on Files.

Common Mistakes

Mixing up a path and a file. A Path is just a name; the file may or may not exist.

Ignoring IOException. File operations can fail for many reasons: missing files, permissions, full disks.

Hard-coding \ or / in paths. Use Path.of("a", "b") or resolve, which use the right separator.

Interview Corner

What is the difference between java.io.File and java.nio.file.Path?

java.io.File is the original Java 1.0 class representing a file path together with operations on it; many of its methods return boolean instead of throwing exceptions, and it has limited support for links, permissions and attributes. java.nio.file.Path, added in Java 7 as part of NIO.2, represents only the path, while the Files utility class provides operations that throw descriptive exceptions, support symbolic links, attributes, permissions, directory walking and simple one-line reading and writing. New code should use Path and Files; file.toPath() and path.toFile() convert between them.

Practice

  1. Easy: Create a folder notes, write a file with three lines into it, and print the number of lines.
  2. Harder: Write a program that creates backup/2026-11-12/ (using today's date) and copies a file into it.

Quick check: File handling

4 questions
1Which API is recommended for new code?
2What does a Path represent?
3Which method reads all lines of a text file?
4How do you convert a File to a Path?

Key Takeaways

Was this tutorial helpful?

Lesson 353 of 482