[英]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() 以字節為單位返回什么而不是文件的內容.. 如您所見,在這里,我正在嘗試閱讀字符。
您可以使用JFileChooser
來選擇一個文件,而不是使用文件閱讀器打開文件,並且在您遍歷文件時只增加一個計數器,就像這樣......
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.