Number of lines in a file in Java

前端 未结 19 2355
抹茶落季
抹茶落季 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 05:56

    I have implemented another solution to the problem, I found it more efficient in counting rows:

    try
    (
       FileReader       input = new FileReader("input.txt");
       LineNumberReader count = new LineNumberReader(input);
    )
    {
       while (count.skip(Long.MAX_VALUE) > 0)
       {
          // Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
       }
    
       result = count.getLineNumber() + 1;                                    // +1 because line index starts at 0
    }
    

提交回复
热议问题