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 to recursively rename files with a specific suffix in Java?

The following code snippet show you how to recursively rename files with a specific suffix. In this example we are renaming a collection of resource bundles files which ends with _in.properties into _id.properties. The code snippet also count the number of files affected by the process. We use the Files.move() method to rename the file, if you want to copy the files instead of renaming them, then you can use the Files.copy() method.

Here is the complete code snippet:

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

public class RenameResourceBundles {
    public static void main(String[] args) {
        String startDirectory = "C:/Projects/Hello";
        AtomicInteger counter = new AtomicInteger(0);

        try (Stream<Path> paths = Files.walk(Paths.get(startDirectory))) {
            paths.filter(Files::isRegularFile)
                    .filter(path -> path.toString().endsWith("_in.properties"))
                    .forEach(path -> renameFile(path, counter));
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Total files renamed: " + counter.get());
    }

    private static void renameFile(Path path, AtomicInteger counter) {
        try {
            String newName = path.toString().replace("_in.properties", "_id.properties");
            Path newPath = Paths.get(newName);
            Files.move(path, newPath);
            System.out.println("Renamed: " + path + " to " + newPath);
            counter.incrementAndGet();
        } catch (IOException e) {
            System.out.println("Failed to rename: " + path);
            e.printStackTrace();
        }
    }
}

This code will recursively search through all subdirectories starting from the specified root directory and rename any files that end with _in.properties to _id.properties. The process prints the renamed file, and finally outputs the total number of files that were successfully renamed after traversing the directory tree.

The explanation of the code snippet above:

  • The Files.walk method is used to traverse the directory tree starting from the given directory.
  • The filter method is used to select only regular files that end with _in.properties.
  • The renameFile method handles the renaming of each file, replacing _in.properties with _id.properties.
  • An AtomicInteger named counter keeps track of the number of files renamed. AtomicInteger is used to handle the count in a thread-safe manner, which is useful if the code is ever modified to use parallel streams or multi-threading.
  • Inside the renameFile method, counter.incrementAndGet() is called each time a file is successfully renamed. This increments the counter by one.
  • After the Files.walk operation, the total number of renamed files is printed using System.out.println("Total files renamed: " + counter.get());.

How do I use Files.walk() method to read directory contents?

The Files.walk() method in Java is a handy method when it comes to reading directory contents. Files.walk() method returns a Stream object that you can use to process each of the elements (files or directories) in the directory structure.

This method walks the file tree in a depth-first manner, starting from the given path that you provide as its parameter. It visits all files and directories in the file tree.

Here’s a simple example of how to use it. In this case, we are printing out the path to each file/directory.

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FileWalkExample {
    public static void main(String[] args) {
        Path start = Paths.get("D:/Games");
        try (Stream<Path> stream = Files.walk(start)) {
            stream.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Files.walk() also supports a maximum depth argument, so you can limit how deep into the directory structure you want to go. For example, Files.walk(start, 2) would only go two levels deep.

Please note: You should always close the stream after you’re done with it to free up system resources. This is done automatically here with a try-with-resources statement.