从JFileChooser Java中检索文件中的行数

问题描述 投票:0回答:2

Java中有没有办法知道所选文件的行数?方法chooser.getSelectedFile().length()是迄今为止我见过的唯一方法,但我找不到如何找到文件中的行数(甚至是字符数)

感谢任何帮助,谢谢。

--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();
}

这是我试过的,但最后读取的变量的数量是<totLength的数量,我不知道File.length()返回的是字节以外的字节数。正如你所看到的,我在这里尝试阅读角色。

java character line jfilechooser
2个回答
0
投票

沮丧和肮脏:

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

您可能会发现这个小方法很方便。它为您提供了忽略文件中空白行计数的选项:

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;
}

0
投票

您可以使用JFileChooser来选择文件,而不是使用文件阅读器打开文件,当您遍历文件时只需递增一个计数器,就像这样......

while (file.hasNextLine()) {
    count++;
    file.nextLine();
}
© www.soinside.com 2019 - 2024. All rights reserved.