Number of lines in a file in Java

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

    It seems that there are a few different approaches you can take with LineNumberReader.

    I did this:

    int lines = 0;
    
    FileReader input = new FileReader(fileLocation);
    LineNumberReader count = new LineNumberReader(input);
    
    String line = count.readLine();
    
    if(count.ready())
    {
        while(line != null) {
            lines = count.getLineNumber();
            line = count.readLine();
        }
        
        lines+=1;
    }
        
    count.close();
    
    System.out.println(lines);
    

    Even more simply, you can use the Java BufferedReader lines() Method to return a stream of the elements, and then use the Stream count() method to count all of the elements. Then simply add one to the output to get the number of rows in the text file.

    As example:

    FileReader input = new FileReader(fileLocation);
    LineNumberReader count = new LineNumberReader(input);
    
    int lines = (int)count.lines().count() + 1;
        
    count.close();
    
    System.out.println(lines);
    

提交回复
热议问题