Number of lines in a file in Java

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

    /**
     * Count file rows.
     *
     * @param file file
     * @return file row count
     * @throws IOException
     */
    public static long getLineCount(File file) throws IOException {
    
        try (Stream lines = Files.lines(file.toPath())) {
            return lines.count();
        }
    }
    

    Tested on JDK8_u31. But indeed performance is slow compared to this method:

    /**
     * Count file rows.
     *
     * @param file file
     * @return file row count
     * @throws IOException
     */
    public static long getLineCount(File file) throws IOException {
    
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file), 1024)) {
    
            byte[] c = new byte[1024];
            boolean empty = true,
                    lastEmpty = false;
            long count = 0;
            int read;
            while ((read = is.read(c)) != -1) {
                for (int i = 0; i < read; i++) {
                    if (c[i] == '\n') {
                        count++;
                        lastEmpty = true;
                    } else if (lastEmpty) {
                        lastEmpty = false;
                    }
                }
                empty = false;
            }
    
            if (!empty) {
                if (count == 0) {
                    count = 1;
                } else if (!lastEmpty) {
                    count++;
                }
            }
    
            return count;
        }
    }
    

    Tested and very fast.

提交回复
热议问题