gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:38:57 24 4
gpt4 key购买 nike

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

感谢任何帮助,谢谢。

--更新--

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() 除了文件内容之外以字节为单位返回什么。可以看到,这里我正在尝试读取字符。

最佳答案

又脏又脏:

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

关于java - 从 JFileChooser Java 检索文件中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54757885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com