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 May 21, 2015 in JSP by rajesh
0 votes

Related Hot Questions

2 Answers

0 votes

From this page the one-line solution:

 String text = new Scanner( new File("poem.txt") ).useDelimiter("\\A").next();


String text = new Scanner( new File("poem.txt"), "UTF-8" ).useDelimiter("\\A").next();

If you want to set the charset

answered May 21, 2015 by rajesh
0 votes
Guava has a method similar to the one from Commons IOUtils that Willi aus Rohr mentioned:


// ...

String text = Files.toString(new File(path), Charsets.UTF_8);
EDIT by Oscar Reyes

This is the (simplified) underlying code on the cited library:

InputStream in = new FileInputStream(file);
byte[] b  = new byte[file.length()];
int len = b.length;
int total = 0;

while (total < len) {
  int result =, total, len - total);
  if (result == -1) {
  total += result;

return new String( b , Charsets.UTF_8 );
Edit (by Jonik): The above doesn't match the source code of recent Guava versions. For the current source, see the classes Files, CharStreams, ByteSource and CharSource in package.
answered May 21, 2015 by rajesh