DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Rick is a DZone Zone Leader and has posted 36 posts at DZone. You can read more from them at their website. View Full User Profile

Speeding Up Java I/O - Read Method

05.17.2008
| 9614 views |
  • submit to reddit
        The following example counts the number of newline bytes ('\n') in a file. It simply uses the read method on a FileInputStream: 

 import java.io.*;
  
  public class intro1 {
    public static void main(String args[]) {
      if (args.length != 1) {
        System.err.println("missing filename");
        System.exit(1);
      }
      try {
        FileInputStream fis =
            new FileInputStream(args[0]);
        int cnt = 0;
        int b;
        while ((b = fis.read()) != -1) {
          if (b == '\n')
            cnt++;
        }
        fis.close();
        System.out.println(cnt);
      }
      catch (IOException e) {
        System.err.println(e);
      }
    }
  }

Subject to Sun's <a href="http://developers.sun.com/license/berkeley_license.html">Code Sample License</a>

 import java.io.*;
  
  public class intro1 {
    public static void main(String args[]) {
      if (args.length != 1) {
        System.err.println("missing filename");
        System.exit(1);
      }
      try {
        FileInputStream fis =
            new FileInputStream(args[0]);
        int cnt = 0;
        int b;
        while ((b = fis.read()) != -1) {
          if (b == '\n')
            cnt++;
        }
        fis.close();
        System.out.println(cnt);
      }
      catch (IOException e) {
        System.err.println(e);
      }
    }
  }
    

Comments

Frank Dietrich replied on Wed, 2008/09/24 - 3:55am

for larger files the Reader classes from Java do the better job import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CountLines { public static void main(String[] args) { if (args.length != 1) { System.err.println("missing filename"); System.exit(1); } try { BufferedReader br = new BufferedReader( new FileReader(args[0])); int cnt = 0; int b; while (br.readLine() != null) { cnt++; } br.close(); System.out.println(cnt); } catch (IOException e) { System.err.println(e); } } }