Learn to read a text file into String in Java. Following examples use Files.readAllBytes()
, Files.lines()
(to read line by line) and FileReader
and BufferedReader
to read a file to String.
1. Using Files.readString() – Java 11
With the new method readString() introduced in Java 11, it takes only a single line to read a file’s content into String
using the UTF-8
charset
.
- In case of any error during the read operation, this method ensures that the file is properly closed.
- It throws
OutOfMemoryError
if the file is extremely large, for example, larger than2GB
.
Path filePath = Path.of("c:/temp/demo.txt");
String content = Files.readString(fileName);
2. Using Files.lines() – Java 8
The lines() method reads all lines from a file into a Stream. The Stream is populated lazily when the stream is consumed.
- Bytes from the file are decoded into characters using the specified charset.
- The returned stream contains a reference to an open file. The file is closed by closing the stream.
- The file contents should not be modified during the reading process, or else the result is undefined.
Path filePath = Path.of("c:/temp/demo.txt");
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder.append(s).append("\n"));
} catch (IOException e) {
//handle exception
}
String fileContent = contentBuilder.toString();
3. Using Files.readAllBytes() – Java 7
The readAllBytes() method reads all the bytes from a file into a byte[]. Do not use this method for reading large files.
This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all the bytes, we pass those bytes to String
class constructor to create a new String.
Path filePath = Path.of("c:/temp/demo.txt");
String fileContent = "";
try {
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
fileContent = new String (bytes);
} catch (IOException e) {
//handle exception
}
4. Using BufferedReader – Java 6
If you are still not using Java 7 or later, then use BufferedReader class. Its readLine()
method reads the file one line at a time and returns the content.
Path filePath = Path.of("c:/temp/demo.txt");
String fileContent = "";
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
contentBuilder.append(sCurrentLine).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
fileContent = contentBuilder.toString();
5. Commons IO’s FileUtils
We can use the utility classes provided by the Apache Commons IO library. The FileUtils.readFileToString() is an excellent way to read a whole file into a String in a single statement.
File file = new File("c:/temp/demo.txt");
String content = FileUtils.readFileToString(file, "UTF-8");
6. Guava’s Files
Guava also provides Files class that can be used to read the file content in a single statement.
File file = new File("c:/temp/demo.txt");
String content = com.google.common.io.Files.asCharSource(file, Charsets.UTF_8).read();
Use any of the above-given methods for reading a file into a string using Java.
Happy Learning !!