FileWriter writer = new FileWriter(output_file);
int i = 0;
try (Stream<String> lines = Files.lines(Paths.get(input_file))) {
lines.forEach(line -> {
try {
writer.write(i + " # " + line + System.lineSeparator());
} catch (Exception e) {
e.printStackTrace();
}
}
);
writer.close();
}
我需要用行号写行,所以我尝试在 .forEach() 中添加一个计数器,但我无法让它工作。我只是不知道把 i++ 放在哪里;进入代码,到目前为止,随意乱搞并没有帮助。
最佳答案
您可以使用 AtomicInteger
作为可变 final
计数器。
public void test() throws IOException {
// Make sure the writer closes.
try (FileWriter writer = new FileWriter("OutFile.txt") ) {
// Use AtomicInteger as a mutable line count.
final AtomicInteger count = new AtomicInteger();
// Make sure the stream closes.
try (Stream<String> lines = Files.lines(Paths.get("InFile.txt"))) {
lines.forEach(line -> {
try {
// Annotate with line number.
writer.write(count.incrementAndGet() + " # " + line + System.lineSeparator());
} catch (Exception e) {
e.printStackTrace();
}
}
);
}
}
}
关于java - 如何将计数器插入 Stream<String> .forEach()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30211153/