Q: Number of lines in a file in Java

D: I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file. I was wondering if there is a smarter way to do that

Test Case #3


File ID: #453067-0-cc


public class Util {
    public static int countLines(String filename) throws IOException {
            InputStream is = new BufferedInputStream(new FileInputStream(filename));
            try {
                byte[] c = new byte[1024];
                int count = 0;
                int readChars = 0;
                boolean empty = true;
                while ((readChars = is.read(c)) ! = -1) {
                    empty = false;
                    for (int i = 0; i < readChars; + +i) {
                        if (c[i] = = '\n')
                            + +count;
                    }
                }
                return (count = = 0 && !empty) ? 1 : count;
            } finally {
                is.close();
            }
        }
}

  1. You are going to close that InputStream when you are done with it, are not you?
  2. Two things: (1) The definition of a line terminator in Java source is a carriage return, a line feed, or a carriage return followed by a line feed. Your solution will not work for CR used as a line terminator. Granted, the only OS of which I can think that uses CR as the default line terminator is Mac OS prior to Mac OS X. (2) Your solution assumes a character encoding such as US-ASCII or UTF-8. The line count may be inaccurate for encodings such as UTF-16.
  3. If buffering helped it would because BufferedInputStream buffers 8K by default. Increase your byte[] to this size or larger and you can drop the BufferedInputStream. e.g. try 1024*1024 bytes.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: