You can use an AtomicInteger
as a mutable final
counter.
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();
}
}
);
}
}
}