API for simple File (line count) functions in Java

后端 未结 4 1128
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-06 05:12

Hi : Given an arbitrary file (java), I want to count the lines.

This is easy enough, for example, using Apache\'s FileUtils.readLines(...) method...

Howeve

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 06:04

    Java 8 short way:

     Files.lines(Paths.get(fileName)).count();
    

    But most memory effiecint:

    try(InputStream in = new BufferedInputStream(new FileInputStream(name))){
        byte[] buf = new byte[4096 * 16];
        int c;
        int lineCount = 0;
        while ((c = in.read(buf)) > 0) {
           for (int i = 0; i < c; i++) {
               if (buf[i] == '\n') lineCount++;
           }
        }
    }
    

    You do not need String objects in this task at all.

提交回复
热议问题