Number of lines in a file in Java

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

    A straight-forward way using Scanner

    static void lineCounter (String path) throws IOException {
    
            int lineCount = 0, commentsCount = 0;
    
            Scanner input = new Scanner(new File(path));
            while (input.hasNextLine()) {
                String data = input.nextLine();
    
                if (data.startsWith("//")) commentsCount++;
    
                lineCount++;
            }
    
            System.out.println("Line Count: " + lineCount + "\t Comments Count: " + commentsCount);
        }
    

提交回复
热议问题