Tuesday, October 16, 2012

Read the whole file and return the content without newlines in Java

This is a simple method to read whole file and take as a string without newlines

[sourcecode language="java"]
public static String readFile(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine);
}
//remove newlines
String newString = sb.toString().replace('\n', ' ');

return newString;
}
[/sourcecode]

No comments:

Post a Comment