Number of lines in a file in Java

前端 未结 19 2555
抹茶落季
抹茶落季 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:02

    if you use this

    public int countLines(String filename) throws IOException {
        LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
        int cnt = 0;
        String lineRead = "";
        while ((lineRead = reader.readLine()) != null) {}
    
        cnt = reader.getLineNumber(); 
        reader.close();
        return cnt;
    }
    

    you cant run to big num rows, likes 100K rows, because return from reader.getLineNumber is int. you need long type of data to process maximum rows..

提交回复
热议问题