readString and writeString
- Java course
- Advanced
- Lesson 69/82
- 5 min
Learn text I/O with Files.readString and writeString.
readString and writeString
In Java 11+, Files.writeString(path, text) writes text to a file; Files.readString(path) reads all text in one go. This is ideal for small and medium files.
Path p = Files.createTempFile("d", ".txt");
Files.writeString(p, "Hello");
String s = Files.readString(p);
// s equals "Hello"This is much shorter than the old BufferedReader chain. UTF-8 is the default encoding; for a different encoding, call with StandardCharsets. For large files, mind the memory consumption.
Specifying encoding
The default encoding is UTF-8. If a different encoding is needed, specify it as Files.readString(p, StandardCharsets.ISO_8859_1).
import java.nio.charset.StandardCharsets;
String s = Files.readString(p, StandardCharsets.UTF_8);UTF-8 is safe for files with Turkish characters. Wrong encoding makes characters look broken. This is a common source of bugs in international applications; be careful.
Practice Write and read text
Write main in a StringDemo class; create a temp file with Files.createTempFile("d", ".txt"). Write text with Files.writeString(p, "Hello"). Read it back with String s = Files.readString(p). Print with System.out.println(s).
Starter code
import java.nio.file.*;
// Write main in StringDemo
// Create temp file; write with writeString; read with readString; printSample solution
import java.nio.file.*;
class StringDemo {
public static void main(String[] args) throws Exception {
Path p = Files.createTempFile("d", ".txt");
Files.writeString(p, "Hello");
String s = Files.readString(p);
System.out.println(s);
}
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match readString/writeString concepts
| Term | Meaning |
|---|---|
writeString |
Writes text to a file |
readString |
Reads all text |
createTempFile |
Creates a temp file |
Files.exists |
Checks existence |
2 Complete the readString call
Path p = Files.createTempFile("d", ".txt");
Files.writeString(p, "Merhaba");
String s = Files.____(p);
Path p = Files.createTempFile("d", ".txt");
Files.writeString(p, "Merhaba");
String s = Files.readString(p);
Explanation: readString reads all text in one go.
3 In which version was Files.readString added?
- Java 11 Correct answer
- Java 8
- Java 9
- Java 10
Explanation: readString was added in Java 11.