title: Java -- reading from a file. Input stream vs. reader
body: <p>In every Java implementation I see of reading from a file, I almost always see a file reader used to read line by line. My thought would be that this would be terribly inefficient because it requires a system call per line.</p>
  
  <p>What I'd been doing instead is to use an input stream and grab the bytes directly. In my experiments, this is significantly faster. My test was a 1MB file.</p>
  
  <pre><code>    //Stream method
      try {
          Long startTime = new Date().getTime();
  
          InputStream is = new FileInputStream("test");
          byte[] b = new byte[is.available()];
          is.read(b);
          String text = new String(b);
          //System.out.println(text);
  
          Long endTime = new Date().getTime();
          System.out.println("Text length: " + text.length() + ", Total time: " + (endTime - startTime));
  
      }
      catch (Exception e) {
          e.printStackTrace();
      }
  
      //Reader method
      try {
          Long startTime = new Date().getTime();
  
          BufferedReader br = new BufferedReader(new FileReader("test"));
          String line = null;
          StringBuilder sb = new StringBuilder();
          while ((line = br.readLine()) != null) {
              sb.append(line);
              sb.append("\n");
          }
          String text = sb.toString();
  
          Long endTime = new Date().getTime();
          System.out.println("Text length: " + text.length() + ", Total time: " + (endTime - startTime));
  
      }
      catch (Exception e) {
          e.printStackTrace();
      }
  </code></pre>
  
  <p>This gives a result of:</p>
  
  <pre><code>Text length: 1054631, Total time: 9
  Text length: 1034099, Total time: 22
  </code></pre>
  
  <p>So, why do people use readers instead of streams?</p>
  
  <p>If I have a method that takes a text file and returns a String that contains all of the text, is it necessarily better to do it using a stream?</p>