Tuesday 21 April 2009

Java Method to Read Text File Contents Into a String

This Java method takes a File as a parameter and returns the text contents of that file as a String.

private static String readFileToString(File f) throws IOException {
StringBuffer sb = new StringBuffer(1000);
BufferedReader br = new BufferedReader(new FileReader(f));
char[] buf = new char[1024];
int readSoFar = 0;
while((readSoFar = br.read(buf)) != -1) {
sb.append(String.valueOf(buf, 0, readSoFar));
buf = new char[1024];
}
br.close();
return sb.toString();
}

It can be modified to take the qualified file name as a String

private static String readFileToString(String f) throws IOException {
...

Done.

No comments: