In this post, we will learn “How to read the content of file to a string in Java 11?”. Java 11 introduced readString() API to do that.
Here, we are going to learn following things:
- What is readString() API?
- How to use it?
Read content of a File to a String in Java 11 using readString methods?...!!! Share on X
Let’s Begin,
1. What is readString() API?
Java 11 introduced two new overloaded methods as part of java.nio.file.Files class.
readString(Path path):
This method reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.
This method is equivalent to: readString(path, StandardCharsets.UTF_8)

readString(Path path, Charset cs):
Reads all characters from a file into a string, decoding from bytes to characters using the specified charset. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.
This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.

2. How to use it?
Let’s take an example where we have a File (TestingFile.txt) which has some text written on that. Now, we are going to read that and write into a string using readString API.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Read_File_To_String_Java11 {
public static void main(String[] args) {
var File_Path = Paths.get("/Users/d33p4k/Docs/TestingFile.txt");
try {
var File_Content = Files.readString(File_Path);
System.out.println("String present in the file is: " + File_Content);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Output:
String present in the file is: This is just for testing.
Read content of a File to a String in Java 11 using readString methods?...!!! Share on X
Do you like this Post? – then check my other helpful posts: