Chapter 69 of 77

File Handling in Java

In many real applications, we need to work with files. For example, a program might need to create a file, read information from a file, write data to a file, or check whether a file exists.

Java provides several classes for working with files. In modern Java, the java.nio.file package is commonly used for this.

Creating a File

We can use the Path and Files classes to work with files.

First, import them:

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

Now we can create a path for a file:

Path path = Paths.get("notes.txt");

To create the file:

Files.createFile(path);

If everything goes correctly, a file named notes.txt will be created in the program's working directory. If the file already exists, createFile() throws a FileAlreadyExistsException.

Paths.get("notes.txt") and Path.of("notes.txt") do the same thing. Path.of() was added in Java 11 and is the shorter, modern form, so the rest of this chapter uses it.

Because file operations can cause exceptions, we usually handle them with try-catch.

try {
    Path path = Paths.get("notes.txt");

    Files.createFile(path);

    System.out.println("File created.");
} catch (Exception e) {
    System.out.println("Something went wrong.");
}

Writing to a File

We can write text to a file using Files.writeString().

import java.nio.file.Files;
import java.nio.file.Path;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("notes.txt");

            Files.writeString(path, "Hello, John!");

            System.out.println("Data written to file.");

        } catch (Exception e) {
            System.out.println("Something went wrong.");
        }
    }
}

After running the program, notes.txt will contain:

Hello, John!

If the file doesn't exist, writeString() creates it. If it already exists, its old content is replaced. (Files.writeString() and Files.readString() were added in Java 11 and use UTF-8 by default.)

Reading from a File

We can read the contents of a text file using Files.readString().

import java.nio.file.Files;
import java.nio.file.Path;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("notes.txt");

            String content = Files.readString(path);

            System.out.println(content);

        } catch (Exception e) {
            System.out.println("Something went wrong.");
        }
    }
}

If notes.txt contains:

Hello, John!
Welcome to Java.

the program will print:

Hello, John!
Welcome to Java.

Checking Whether a File Exists

Before reading or modifying a file, we may want to check whether it actually exists.

We can use Files.exists():

Path path = Path.of("notes.txt");

if (Files.exists(path)) {
    System.out.println("File exists.");
} else {
    System.out.println("File does not exist.");
}

This is useful because trying to read a file that doesn't exist can cause an exception.

Deleting a File

We can delete a file using Files.delete().

import java.nio.file.Files;
import java.nio.file.Path;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("notes.txt");

            Files.delete(path);

            System.out.println("File deleted.");

        } catch (Exception e) {
            System.out.println("Could not delete the file.");
        }
    }
}

If the file doesn't exist, the operation will fail, so handling the exception is important.

Appending Data to a File

Sometimes we don't want to replace the existing content. We want to add new content at the end of the file.

For this, we can use StandardOpenOption.APPEND.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("notes.txt");

            Files.writeString(
                path,
                "\nWelcome to Java!",
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND
            );

        } catch (Exception e) {
            System.out.println("Something went wrong.");
        }
    }
}

If the file already contains:

Hello, John!

after running the program it will contain:

Hello, John!
Welcome to Java!

The APPEND option tells Java to add the new content instead of replacing the existing content.

Reading Lines from a File

Sometimes we want to process a file one line at a time.

We can use Files.readAllLines():

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("students.txt");

            List<String> students = Files.readAllLines(path);

            for (String student : students) {
                System.out.println(student);
            }

        } catch (Exception e) {
            System.out.println("Could not read the file.");
        }
    }
}

If the file contains:

John
Jason
Alex

the program prints:

John
Jason
Alex

This can be useful when working with simple text files containing lists of data.

File and Directory Information

The Files class also allows us to check whether a path represents a file or a directory.

For example:

Path path = Path.of("notes.txt");

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

If notes.txt is a normal file, the output will be:

true
false

We can also check whether we have permission to read or write:

Files.isReadable(path);
Files.isWritable(path);

File Handling and Exceptions

File operations can fail for many reasons. The file might not exist, the program might not have permission to access it, or the path might be invalid.

That's why you'll often see file-handling code inside a try-catch block.

For example:

try {
    String content = Files.readString(Path.of("notes.txt"));

    System.out.println(content);

} catch (Exception e) {
    System.out.println("Unable to read the file.");
}

Later, you can handle specific exceptions more precisely instead of catching the general Exception class. Most file methods throw IOException, which is a checked exception, so the compiler forces you to either catch it or declare it with throws.

BufferedReader, BufferedWriter and try-with-resources

You will also see the older java.io classes in many programs and interview questions. They are useful for reading or writing large files line by line:

import java.io.*;

try (BufferedWriter writer = new BufferedWriter(new FileWriter("students.txt"))) {
    writer.write("John");
    writer.newLine();
    writer.write("Jason");
} catch (IOException e) {
    System.out.println("Could not write the file.");
}

try (BufferedReader reader = new BufferedReader(new FileReader("students.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.out.println("Could not read the file.");
}

Output:

John
Jason

The try (...) form is called try-with-resources. Any resource created inside the parentheses is closed automatically when the block ends, even if an exception occurs. Always close files, either this way or in a finally block, otherwise data may not be written and the file may stay locked.

A Complete Example

Let's create a simple program that writes and then reads a file:

import java.nio.file.Files;
import java.nio.file.Path;

class Main {
    public static void main(String[] args) {

        try {
            Path path = Path.of("message.txt");

            Files.writeString(
                path,
                "Hello, John!\nWelcome to Java."
            );

            String content = Files.readString(path);

            System.out.println(content);

        } catch (Exception e) {
            System.out.println("File operation failed.");
        }
    }
}

Output:

Hello, John!
Welcome to Java.

Here, the program first writes data to the file and then reads the same data back.

The main idea is simple: file handling allows a Java program to communicate with files stored on the computer. You can create, read, write, append, check, and delete files using classes such as Path and Files from the java.nio.file package.