Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases):</p> <pre><code>BufferedReader br = new BufferedReader(new FileReader("file.txt")); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } </code></pre> <p>Some has pointed out that after Java 7 you should use <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">try-with-resources</a> (i.e. auto close) features:</p> <pre><code>try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } </code></pre> <p>When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.</p> <p>Though if I want to actually just read a file into a String, I always use Apache <a href="http://commons.apache.org/proper/commons-io/">Commons IO</a> with the class IOUtils.toString() method. You can have a look at the source here:</p> <p><a href="http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html">http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html</a></p> <pre><code>FileInputStream inputStream = new FileInputStream("foo.txt"); try { String everything = IOUtils.toString(inputStream); } finally { inputStream.close(); } </code></pre> <p>And even simpler with Java 7:</p> <pre><code>try(FileInputStream inputStream = new FileInputStream("foo.txt")) { String everything = IOUtils.toString(inputStream); // do something with everything string } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload