Files.readString() and Files.writeString() in Java 11
Java 11 added Files.readString(Path) and Files.writeString(Path, CharSequence, OpenOption...) to java.nio.file.Files. They read or write a whole text file in a single call and use UTF-8 unless you pass another charset.
This tutorial shows both methods, how to append, how they compare with older code, and when not to use them.
1. Why Were These Methods Added?
Reading a small text file used to need a BufferedReader loop, or new String(Files.readAllBytes(path), charset). Both are easy to get wrong, especially the charset. The new methods make the common case one readable line with a sensible default.
2. Method Signatures
static String readString(Path path) throws IOException // UTF-8
static String readString(Path path, Charset cs) throws IOException
static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOException
static Path writeString(Path path, CharSequence csq, Charset cs, OpenOption... options) throws IOException
Without options, writeString creates the file or truncates an existing one, like CREATE, TRUNCATE_EXISTING and WRITE.
3. Practical Examples
Example 1: Write, append and read
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class ReadWriteString {
public static void main(String[] args) throws IOException {
Path notes = Files.createTempFile("notes", ".txt");
// writeString: one call, UTF-8 by default, returns the path
Files.writeString(notes, "Buy milk\n");
// Options work as with Files.write, e.g. APPEND
Files.writeString(notes, "Pay rent\n", StandardOpenOption.APPEND);
// readString: the whole file as one String (UTF-8 by default)
String content = Files.readString(notes);
System.out.print(content);
System.out.println("Characters: " + content.length());
// A charset can be passed explicitly
Files.writeString(notes, "Café ₹50", StandardCharsets.UTF_8);
System.out.println("Read back : " + Files.readString(notes, StandardCharsets.UTF_8));
System.out.println("Bytes : " + Files.size(notes));
Files.delete(notes);
}
}
Buy milk Pay rent Characters: 18 Read back : Café ₹50 Bytes : 11
The text Café ₹50 has 8 characters but 11 bytes in UTF-8, because é needs 2 bytes and ₹ needs 3.
Example 2: Old and new code side by side
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 BeforeAndAfter {
// Before Java 11: read all bytes and decode, or loop with a reader
static String readOld(Path file) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
Path config = Files.createTempFile("app", ".properties");
Files.writeString(config, "port=8080\nmode=dev\n");
String before = readOld(config);
String after = Files.readString(config); // Java 11: one line
System.out.println("Same content: " + before.equals(after));
// Combine with String.lines() from Java 11
after.lines()
.filter(l -> l.startsWith("port"))
.forEach(l -> System.out.println("Found " + l));
try {
Files.readString(config.resolveSibling("missing.properties"));
} catch (IOException e) {
System.out.println("Missing file: " + e.getClass().getSimpleName());
}
Files.delete(config);
}
}
Same content: true Found port=8080 Missing file: NoSuchFileException
4. How readString Works
5. Important Points and Best Practices
- Use them for small files such as configuration, templates and test data; for large files use
Files.linesor aBufferedReader. readStringthrowsMalformedInputExceptionif the bytes are not valid in the charset, instead of replacing them silently.- Pass
StandardOpenOption.APPENDto add to a file andCREATE_NEWto fail if it already exists. - Missing files cause
NoSuchFileException, a subclass ofIOException.
6. Summary
- Java 11 added
Files.readStringandFiles.writeString. - Both use UTF-8 by default and accept an explicit
Charset. writeStringaccepts open options such asAPPEND.- They load the whole file into memory, so use streaming APIs for big files.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. Which charset does Files.readString use?
UTF-8, unless you pass another Charset as the second argument.
Q2. Does Files.writeString overwrite an existing file?
Yes, by default it truncates the file. Pass StandardOpenOption.APPEND to add to the end instead.
Q3. Is Files.readString suitable for large files?
Not really. It loads the whole file into one String. For large files, process lines lazily with Files.lines or a BufferedReader.
Q4. What happens if the file contains invalid UTF-8?
readString throws a MalformedInputException rather than inserting replacement characters.