Search code examples
javaswingcharacterlinejfilechooser

Retrieve number of lines in file from JFileChooser Java


Is there a way in Java to know the number of lines of a file chosen? The method chooser.getSelectedFile().length() is the only method I've seen so far but I can't find out how to find the number of lines in a file (or even the number of characters)

Any help is appreciated, thank you.

--update--

long totLength = fc.getSelectedFile().length(); // total bytes = 284
double percentuale = 100.0 / totLength;         // 0.352112676056338
int read = 0;

String line = br.readLine();
read += line.length();

Object[] s = new Object[4];

while ((line = br.readLine()) != null)
{
    s[0] = line;
    read += line.length();
    line = br.readLine();
    s[1] = line;
    read += line.length();
    line = br.readLine();
    s[2] = line;
    read += line.length();
    line = br.readLine();
    s[3] = line;
    read += line.length();
}

this is what I tried, but the number of the variable read at the end is < of the totLength and I don't know what File.length() returns in bytes other than the content of the file.. As you can see, here i'm trying to read characters though.


Solution

  • Down and dirty:

    long count =  Files.lines(Paths.get(chooser.getSelectedFile())).count();
    

    You may find this little method handy. It gives you the option to ignore counting blank lines in a file:

    public long fileLinesCount(final String filePath, boolean... ignoreBlankLines) {
        boolean ignoreBlanks = false;
        long count = 0;
        if (ignoreBlankLines.length > 0) {
            ignoreBlanks = ignoreBlankLines[0];
        }
        try {
            if (ignoreBlanks) {
                count =  Files.lines(Paths.get(filePath)).filter(line -> line.length() > 0).count();
            }
            else {
                count =  Files.lines(Paths.get(filePath)).count();
            }
        }
        catch (IOException ex) { 
            ex.printStackTrace(); 
        }
        return count;
    }