我有一个读取文本文件中所有行的方法,我想输出已读取文件的当前百分比。我已经设法做到了,但是,每次读取新行时它都会输出百分比,因此输出如下所示:
0.0% 读取。 0.0% 读取。 0.0% 读取。 1.0% 阅读。 1.0% 阅读。 1.0% 阅读。
依此类推...我希望它每次从 0 变为 1、从 1 变为 2 或类似时输出。这是相关的代码片段:
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
String line = reader.readLine();
// Counts total number of lines
BufferedReader reader2 = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
int totalLines = 0;
while (reader2.readLine() != null) {
totalLines++;
}
// read all lines from file
int lineNumber = 1;
while (line != null) {
float percent = lineNumber * 100f / totalLines;
double x = Math.round(percent);
System.out.println(x + "% read.");
line = reader.readLine();
lineNumber++;
}