Number of lines in a file in Java

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

    I tested the above methods for counting lines and here are my observations for Different methods as tested on my system

    File Size : 1.6 Gb Methods:

    1. Using Scanner : 35s approx
    2. Using BufferedReader : 5s approx
    3. Using Java 8 : 5s approx
    4. Using LineNumberReader : 5s approx

    Moreover Java8 Approach seems quite handy :

    Files.lines(Paths.get(filePath), Charset.defaultCharset()).count()
    [Return type : long]
    

提交回复
热议问题