If the files being read is huge then you would want to use BufferedReader
on top of a FileReader
to improve read performance.
or you may try something likethis:-
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
or you can try this program. It works faster for larger files:-
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}
FileReader
myself - useInputStreamReader
wrappingFileInputStream
, so you can explicitly set the encoding. – Verada