How to read a file to string in Java

Dealing with files in Java involves frequently performing operations like reading the file, converting to a string, etc.

svg viewer

Using BufferedReader class

In the code below my_Reader, the object of BufferedReader class, is used to read the file. The object of StringBuilder is used to append the content to a string after reading it from the file.

main.java
data.txt
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class BufferedReaderExample {
public static void main(String[] args) {
try {
BufferedReader my_Reader = new BufferedReader(new FileReader(new File(
"data.txt")));
String line = "";
StringBuilder str = new StringBuilder();
while((line = my_Reader.readLine()) != null)
{
str.append(line);
}
System.out.println(str);
my_Reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not exists or insufficient rights");
e.printStackTrace();
} catch (IOException e) {
System.out.println("An exception occured while reading the file");
e.printStackTrace();
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved