Course contentsShow
← Java
Lesson 2040 of 2,87041. NIO.2 and the Path APIFree lesson

Writing a String: Files.writeString (Java 11+)

Use Files.writeString to write a single String to a file with proper encoding handling.

Writing a String: Files.writeString (Java 11+)

You'll learn how to write an entire String to a file in one line using Java 11's convenient Files.writeString method with proper character encoding.

The Modern String-to-File Method

While Files.write with Iterable<CharSequence> works for multiple lines and byte arrays handle raw data, Java 11 introduced Files.writeString specifically for the common case of writing a single String to a file. This method handles character encoding automatically and gracefully, making it the cleanest choice for text output.

Think of Files.writeString as a specialized tool designed for one job: converting your String into properly encoded bytes and writing them to a file. It's like having a "save document" button that handles all the technical details behind the scenes.

How It Works

The method signature is straightforward:

Files.writeString(Path path, CharSequence content)

Here's a complete example:

Path file = Paths.get("output.txt");
String message = "Hello, NIO.2 World!\nThis is convenient.";
Files.writeString(file, message);

Specifying Encoding

You can explicitly control character encoding using StandardCharsets:

Files.writeString(file, message, StandardCharsets.UTF_8);

This is the default anyway (UTF-8), but being explicit prevents platform-dependent surprises.

Overwrite vs Append

By default, writeString overwrites existing files. You can append instead:

Files.writeString(file, "\nAdditional line", 
    StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Why Use This Over Alternatives?

Compared to creating a PrintWriter or using Files.write with byte arrays, writeString is more concise when you already have a complete String ready to write. It automatically handles encoding, buffering, and resource management—all in one method call.

Key Takeaway: Files.writeString (Java 11+) provides a one-line solution for writing String content to a file with explicit encoding control, making it the cleanest choice for simple text file operations.