Number of lines in a file in Java

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

    Scanner with regex:

    public int getLineCount() {
        Scanner fileScanner = null;
        int lineCount = 0;
        Pattern lineEndPattern = Pattern.compile("(?m)$");  
        try {
            fileScanner = new Scanner(new File(filename)).useDelimiter(lineEndPattern);
            while (fileScanner.hasNext()) {
                fileScanner.next();
                ++lineCount;
            }   
        }catch(FileNotFoundException e) {
            e.printStackTrace();
            return lineCount;
        }
        fileScanner.close();
        return lineCount;
    }
    

    Haven't clocked it.

提交回复
热议问题