Organizational Research By

Surprising Reserch Topic

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

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?

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


asked Jun 18, 2015 in Core java by rajesh
0 votes

Related Hot Questions

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.