从 java 中的文件中读取多行形成特定行号
reading multi lines form a specific line number from a file in java
如果我有一个包含 10000 行整数的文件,我想从第 100 行读取到第 900 行并将它们相加,那么如何在 java 中执行?
使用流是一件简单的事情。这将对从 start
到 end
的所有数字求和。
String fileName = "some file name";
int start = 100;
int end = 900;
try {
long sum = Files.lines(Path.of(fileName))
// skip the first start - 1 lines
.skip(start-1)
// now allow the next lines up to and including
// the original end number.
.limit(end-start+1)
// covert to an int for summing
.mapToLong(Long::parseLong)
// sum them
.sum();
System.out.print(sum);
} catch (Exception e) {
e.printStackTrace();
}
如果您不想使用流,这里有一个基于循环的版本。我在打印语句中留下了哪些行被跳过与相加。
String fileName = "some file name";
int start = 100;
int end = 1000;
long sum = 0;
try (BufferedReader fr = new BufferedReader(new FileReader(fileName))) {
while (--start > 0) {
end--; // update number to finally read.
// skip first start - 1 lines
String line = fr.readLine();
System.out.println("Skipping " + line);
}
while (end-- > 0) {
String line = fr.readLine().trim();
System.out.println("Summing " + line);
sum += Long.valueOf(line);
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(sum);
可以这样做:
int fromLine = 100;
int toLine = 900;
int result = Files.lines(Path.of("numfile.dat"))
.skip(fromLine - 1).limit(toLine - fromLine)
.mapToInt(Integer::parseInt).sum();
如果我有一个包含 10000 行整数的文件,我想从第 100 行读取到第 900 行并将它们相加,那么如何在 java 中执行?
使用流是一件简单的事情。这将对从 start
到 end
的所有数字求和。
String fileName = "some file name";
int start = 100;
int end = 900;
try {
long sum = Files.lines(Path.of(fileName))
// skip the first start - 1 lines
.skip(start-1)
// now allow the next lines up to and including
// the original end number.
.limit(end-start+1)
// covert to an int for summing
.mapToLong(Long::parseLong)
// sum them
.sum();
System.out.print(sum);
} catch (Exception e) {
e.printStackTrace();
}
如果您不想使用流,这里有一个基于循环的版本。我在打印语句中留下了哪些行被跳过与相加。
String fileName = "some file name";
int start = 100;
int end = 1000;
long sum = 0;
try (BufferedReader fr = new BufferedReader(new FileReader(fileName))) {
while (--start > 0) {
end--; // update number to finally read.
// skip first start - 1 lines
String line = fr.readLine();
System.out.println("Skipping " + line);
}
while (end-- > 0) {
String line = fr.readLine().trim();
System.out.println("Summing " + line);
sum += Long.valueOf(line);
}
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(sum);
可以这样做:
int fromLine = 100;
int toLine = 900;
int result = Files.lines(Path.of("numfile.dat"))
.skip(fromLine - 1).limit(toLine - fromLine)
.mapToInt(Integer::parseInt).sum();