从 JFileChooser 检索文件中的行数 Java
Retrieve number of lines in file from JFileChooser Java
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() returns 除了文件的内容。如您所见,我在这里尝试读取字符。
您可以使用 JFileChooser
来 select 文件,而不是使用文件 reader 打开文件,并且在遍历文件时只需递增一个计数器,就像这样。 ..
while (file.hasNextLine()) {
count++;
file.nextLine();
}
又脏又脏:
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 中有没有办法知道所选文件的行数?
方法 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() returns 除了文件的内容。如您所见,我在这里尝试读取字符。
您可以使用 JFileChooser
来 select 文件,而不是使用文件 reader 打开文件,并且在遍历文件时只需递增一个计数器,就像这样。 ..
while (file.hasNextLine()) {
count++;
file.nextLine();
}
又脏又脏:
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;
}