How do I close a file automatically using try-with-resources in Java?

Use a try-with-resources statement to close a file reader automatically. Java closes the reader when execution leaves the try block, even if reading fails.

In this example, you will open a UTF-8 text file with a BufferedReader and print it one line at a time.

Source code

Save the following code as TryWithResourcesExample.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class TryWithResourcesExample {
    void main() {
        Path path = Path.of("greeting.txt");

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

            while ((line = reader.readLine()) != null) {
                IO.println(line);
            }
        } catch (IOException exception) {
            System.err.println(
                    "Could not open, read, or close the file: "
                            + exception.getMessage());
        }
    }
}

Explanation

The declaration inside the parentheses after try opens the file and creates a BufferedReader:

try (BufferedReader reader =
        Files.newBufferedReader(path, StandardCharsets.UTF_8)) {

A BufferedReader implements AutoCloseable, so Java can call its close() method automatically. Closing the reader also closes the underlying file resource.

Inside the block, readLine() returns the next line without its line separator. It returns null when there are no more lines. The while condition assigns each result to line and checks whether it is null. A blank line returns an empty string, so it is still printed.

When the loop ends, Java closes the reader. If reading throws an exception, Java still attempts to close the reader before running the catch block. You do not need to call close() yourself or add a finally block for cleanup.

Run the example

Reuse greeting.txt from the previous example, or create it as a UTF-8 file with these contents:

Hello, Java!
Learning Java one snippet at a time.

From the directory containing both files, compile and run the program:

javac TryWithResourcesExample.java
java TryWithResourcesExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use try-with-resources when you open a reader or writer yourself. Convenience methods such as Files.readString() and Files.writeString() already manage the file resource for you.

How do I write text to a file using Files.writeString() in Java?

Use Files.writeString() to save a string to a text file. By default, it uses UTF-8, creates the file if it does not exist, and replaces its contents if it already exists.

In this example, you will write a two-line message to a file named greeting.txt.

Source code

Save the following code as WriteStringExample.java:

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

public class WriteStringExample {
    void main() {
        Path path = Path.of("greeting.txt");

        String message = """
                Hello, Java!
                Learning Java one snippet at a time.
                """;

        try {
            Files.writeString(path, message);
            IO.println("Text written to " + path);
        } catch (IOException exception) {
            System.err.println(
                    "Could not write the file: " + exception.getMessage());
        }
    }
}

Explanation

Path.of("greeting.txt") creates a relative path. The program writes the file in its current working directory, which is normally the directory from which you run the java command.

The triple quotes (""") define a text block. This lets you write multiple lines without adding \n between them. Because the closing quotes are on their own line, the string also ends with a newline.

The following statement saves the message:

Files.writeString(path, message);

Files.writeString() encodes the string as UTF-8 and writes it as supplied. It does not add a newline of its own. The method handles opening and closing the file, so there is no writer to close in your code.

The catch block handles an IOException, which can occur if the directory is not writable. The success message appears only if the write completes without throwing an exception.

Run the example

Compile and run the file from a directory where you can create greeting.txt:

javac WriteStringExample.java
java WriteStringExample

The program prints:

Text written to greeting.txt

Open greeting.txt to see its contents:

Hello, Java!
Learning Java one snippet at a time.

Appending instead of replacing

To keep existing contents and add the message at the end, import java.nio.file.StandardOpenOption and replace the write statement with:

Files.writeString(
        path, message,
        StandardOpenOption.CREATE,
        StandardOpenOption.APPEND);

CREATE creates the file if it is missing, and APPEND writes at the end if it already exists. If the existing text does not end with a newline, the appended text starts on the same line.

How do I read a text file using Files.readString() in Java?

You can use Files.readString() to read an entire text file into a single string. It preserves the file’s line separators, so the result can contain multiple lines.

In this example, you will read a UTF-8 text file and display its contents.

Source code

Save the following code as ReadStringExample.java:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class ReadStringExample {
    void main() {
        Path path = Path.of("message.txt");

        try {
            String content = Files.readString(path, StandardCharsets.UTF_8);

            IO.print(content);
        } catch (IOException exception) {
            System.err.println("Could not read the file: " + exception.getMessage());
        }
    }
}

Prepare the text file

Create a file named message.txt in the directory from which you will run the program. Save it using UTF-8 encoding with the following contents:

Hello, Java!
Learning Java one snippet at a time.

Explanation

The example creates a Path representing the file location:

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

This is a relative path. Java resolves it against the program’s current working directory, which may differ from the directory containing the source file.

Reading the contents

The following statement reads the entire file:

String content = Files.readString(path, StandardCharsets.UTF_8);

The first argument identifies the file. The second specifies how its bytes are decoded into characters.

Using StandardCharsets.UTF_8 makes the expected encoding explicit. The overload Files.readString(path) also uses UTF-8.

The method returns one string containing all the text, including any line separators in the file.

Displaying the text

The program prints the contents using:

IO.print(content);

IO.print() does not append a line separator. This lets the program display the text without adding an extra newline beyond those already in the file.

Handling read failures

Files.readString() can throw an IOException, for example when the file is missing or cannot be read.

The catch block handles that failure:

catch (IOException exception) {
    System.err.println("Could not read the file: " + exception.getMessage());
}

The error message goes to standard error, while the file contents go to standard output.

You do not need to close a reader yourself. Files.readString() manages the file resource and closes it when reading finishes or an error occurs.

Run the example

With message.txt in your current directory, compile and run the program:

javac ReadStringExample.java
java ReadStringExample

Output

Hello, Java!
Learning Java one snippet at a time.

Use Files.readString() for files that comfortably fit in memory. For large files, process the contents incrementally with a buffered reader or Files.lines() instead.

How do I use memory mapped files with FileChannel.map()?

Using FileChannel.map() allows you to map a region of a file directly into memory. This creates a MappedByteBuffer, which acts like a bridge between your application’s memory and the file on disk. The operating system handles the actual reading and writing in the background, making it extremely efficient for large files.

Here is how you can use it for both reading and writing.

1. Reading from a Memory-Mapped File

To read, open the channel with StandardOpenOption.READ and use MapMode.READ_ONLY.

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class MemoryMappedExample {
    public void readMappedFile(Path path) throws IOException {
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            long size = channel.size();

            // Map the entire file for reading
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);

            // Access data directly from memory
            while (buffer.hasRemaining()) {
                byte b = buffer.get();
                // Process byte...
            }
        }
    }
}

2. Writing to a Memory-Mapped File

To write, you must open the channel with both READ and WRITE options (even if you only intend to write) and use MapMode.READ_WRITE.

public void writeMappedFile(Path path) throws IOException {
    // Files must be opened for both READ and WRITE to use MapMode.READ_WRITE
    try (FileChannel channel = FileChannel.open(path, 
            StandardOpenOption.READ, 
            StandardOpenOption.WRITE, 
            StandardOpenOption.CREATE)) {

        long size = 1024 * 1024; // Map 1MB
        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, size);

        // Writing to the buffer automatically writes to the file
        buffer.putInt(12345);
        buffer.put("Hello Memory!".getBytes());

        // Force changes to storage to ensure they are written to disk
        buffer.force();
    }
}

Key Considerations

  • Map Modes:
    • READ_ONLY: Any attempt to modify the buffer results in a ReadOnlyBufferException.
    • READ_WRITE: Changes to the buffer are eventually propagated to the file.
    • PRIVATE: “Copy-on-write” mode. Changes are local to the buffer and not saved to the file.
  • Size Limits: On 32-bit JVMs, you cannot map more than 2GB at once because of address space limits. On 64-bit systems, you can map much larger regions, but a single MappedByteBuffer is still limited to Integer.MAX_VALUE bytes (approx 2GB). To handle larger files, you must create multiple mappings.
  • Performance: Memory mapping is most beneficial for large files accessed frequently or randomly. For small, sequential reads, standard BufferedInputStream might be simpler and just as fast.
  • Unmapping: Java does not provide an explicit “unmap” method. The mapping remains until the MappedByteBuffer object is garbage collected. Closing the FileChannel does not unmap the file.

How do I use ObjectOutputStream with record?

To use ObjectOutputStream with a Java record, you need to make the record implement the java.io.Serializable interface.

One of the great things about records is that they are designed to be “data carriers,” and Java’s serialization mechanism handles them more robustly and securely than regular classes. Specifically, records are serialized using only their components (the fields defined in the header), and the deserialization process uses the record’s canonical constructor, ensuring that any validation logic you’ve placed there is always executed.

Here is a complete example of how to write a record to a file and read it back:

1. Define the Record

Make sure it implements Serializable.

package org.kodejava.io;

import java.io.Serializable;

/**
 * A simple record representing a Person.
 * Records are implicitly final and their fields are private and final.
 */
public record Person(String name, int age) implements Serializable {
    // Compact constructor for validation
    public Person {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
    }
}

2. Serialize and Deserialize

Use ObjectOutputStream to write the object and ObjectInputStream to read it.

package org.kodejava.io;

import java.io.*;

public class RecordSerializationDemo {
    public static void main(String[] args) {
        String filename = "person.ser";
        Person person = new Person("John Doe", 30);

        // 1. Serialize the record
        try (FileOutputStream fos = new FileOutputStream(filename);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            oos.writeObject(person);
            System.out.println("Record saved: " + person);

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

        // 2. Deserialize the record
        try (FileInputStream fis = new FileInputStream(filename);
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            Person savedPerson = (Person) ois.readObject();
            System.out.println("Record loaded: " + savedPerson);

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

Key Points to Remember:

  • Immutability: Since records are immutable, serialization is very straightforward.
  • No serialVersionUID Required (mostly): While you can define a serialVersionUID, Java’s serialization for records ignores the field-matching rules that usually require it. The serialization is based strictly on the component names.
  • Security: Records are less susceptible to “deserialization attacks” because they don’t allow the creation of “ghost” objects; they must go through the canonical constructor.
  • Customization: Records do not support writeObject, readObject, readObjectNoData, or writeExternal methods. If you need custom serialization logic, you should use a regular class instead.