Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As suggested by <a href="http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all" rel="nofollow noreferrer">Garrett Rowe and Stan James</a> you can use <code>java.util.Scanner</code>:</p> <pre><code>try (Scanner s = new Scanner(file).useDelimiter("\\Z")) { String contents = s.next(); } </code></pre> <p>or</p> <pre><code>try (Scanner s = new Scanner(file).useDelimiter("\\n")) { while(s.hasNext()) { String line = s.next(); } } </code></pre> <p>This code does not have external dependencies. Here is an example of how to use <code>java.util.Scanner</code> with correct resource and error handling:</p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Iterator; class TestScanner { public static void main(String[] args) throws FileNotFoundException { File file = new File(args[0]); System.out.println(getFileContents(file)); processFileLines(file, new LineProcessor() { @Override public void process(int lineNumber, String lineContents) { System.out.println(lineNumber + ": " + lineContents); } }); } static String getFileContents(File file) throws FileNotFoundException { try (Scanner s = new Scanner(file).useDelimiter("\\Z")) { return s.next(); } } static void processFileLines(File file, LineProcessor lineProcessor) throws FileNotFoundException { try (Scanner s = new Scanner(file).useDelimiter("\\n")) { for (int lineNumber = 1; s.hasNext(); ++lineNumber) { lineProcessor.process(lineNumber, s.next()); } } } static interface LineProcessor { void process(int lineNumber, String lineContents); } } </code></pre>
 

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