Number of lines in a file in Java

前端 未结 19 2273
抹茶落季
抹茶落季 2020-11-22 05:31

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<

相关标签:
19条回答
  • 2020-11-22 06:11

    This funny solution works really good actually!

    public static int countLines(File input) throws IOException {
        try (InputStream is = new FileInputStream(input)) {
            int count = 1;
            for (int aChar = 0; aChar != -1;aChar = is.read())
                count += aChar == '\n' ? 1 : 0;
            return count;
        }
    }
    
    0 讨论(0)
提交回复
热议问题