How to create a Java String from the contents of a file
- by Oscar Reyes
I've been using this idiom for some time now. And it seems to be the most wide spread at least in the sites I've visited.
Does anyone have a better/different way to read a file into a string in Java.
Thanks
private String readFile( String file ) throws IOException {
BufferedReader reader = new BufferedReader( new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while( ( line = reader.readLine() ) != null ) {
stringBuilder.append( line );
stringBuilder.append( ls );
}
return stringBuilder.toString();
}