In Java 11, a new method called readString
was added to the java.nio.file.Files
class to read all content from a file into a string.
This method closes the file once the file is read or any exception is thrown during execution, so we don’t need to worry about closing the file.
There are two overloaded methods:
1. public static String readString(Path path) throws IOException
2. public static String readString(Path path, Charset cs) throws IOException
Using the first method, we can read the file with the “UTF-8” Charset
.
The second method is used to pass a specific Charset
like US_ASCII.
Read more about
Charsets
here.
import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.Files;import java.io.IOException;class Main {public static void main( String args[] ) {Path filePath = Paths.get("./test.txt");try {String fileContent = Files.readString(filePath);System.out.println(fileContent);} catch (IOException e) {e.printStackTrace();}}}
In the code above, we have:
Created a text file with the name test.txt
.
Created the Path
object pointing to the created text file.
Read the content of the file using the Files.readString
method and stored the return file content string to fileContent
variable.
Printed the file content to the console.
Execute the program above here.