Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a stream without assigning it to a variable [Java]

I'm reading a large file using the nio Files.lines method, and writing it to another file.

BufferedWriter writer = Files.newBufferedWriter(Path.of(outFile);

         Files.lines(Path.of(inputFile))
                .forEach(line -> {
                    try {
                        writer.write(line);
                        writer.newLine();
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                });
        writer.flush();
        writer.close();
    

I want to close the writer and the stream (Files.lines) in a finally block. I'm aware I'll have to surround this snippet in a try-catch-finally block, but how do I close the stream without assigning it to a variable?

like image 580
Abhinandan Madaan Avatar asked May 23 '26 01:05

Abhinandan Madaan


1 Answers

Instead of doing lots of manual work, just use the following snippet (as you've been advised already in the comments):

Files.copy(Path.of(inputFile), Path.of(outFile)));

If you still want to do that manually for some reason, use try-with-resources. You will still assign the BufferedWriter to a variable, but there'll be no need to close it explicitly. Java will do that by itself:

try(BufferedWriter writer = Files.newBufferedWriter(Path.of(outFile));
    Stream<String> lines = Files.lines(Path.of(inputFile))) {
    // ... do something with your lines & writer here
}
like image 124
ETO Avatar answered May 24 '26 18:05

ETO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!