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.
