How to create a Java String from the contents of a file

Posted by Oscar Reyes on Stack Overflow See other posts from Stack Overflow or by Oscar Reyes
Published on 2008-11-28T18:32:07Z Indexed on 2010/04/17 10:13 UTC
Read the original article Hit count: 373

Filed under:
|

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();
 }

© Stack Overflow or respective owner

Related posts about java

Related posts about io