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

Files.writeString: Writing Strings Directly (Java 11+)

Use Files.writeString to write a single String to a file in one method call with proper encoding.

Files.writeString: Writing Strings Directly (Java 11+)

You'll learn how to write a complete String to a file in a single method call using Java 11's convenient Files.writeString method.

The Core Idea

Files.writeString is a one-line solution for writing text to a file. Instead of creating a Writer, writing your content, and closing resources, you simply call this static method with a Path and your String. It handles everything—opening the file, writing the text with proper encoding, and closing it automatically.

Think of it like ordering food for delivery: you don't need to drive to the restaurant, pick up the food, and drive back. You just make one call, and everything happens for you.

Basic Usage

Path outputPath = Path.of("output.txt");
String content = "Hello, World!\nThis is a test.";

Files.writeString(outputPath, content);

That's it! The file is created (or overwritten), the String is written with UTF-8 encoding by default, and the file is properly closed.

Specifying Encoding

You can specify a Charset if you need something other than UTF-8:

Files.writeString(outputPath, content, StandardCharsets.ISO_8859_1);

Controlling File Creation

You can pass OpenOption parameters to control behavior like appending:

Files.writeString(outputPath, content, StandardOpenOption.APPEND);

This adds your String to the end of an existing file rather than replacing it.

When to Use It

Use Files.writeString when you have a complete String ready to write and want the simplest possible code. For line-by-line writing or very large amounts of data, use newBufferedWriter instead for better memory efficiency.

Key Takeaway: Files.writeString writes a single String to a file in one method call, handling encoding (UTF-8 by default), file operations, and resource cleanup automatically—perfect for simple, complete text output scenarios.