Should I always close BufferedReader?Does collect operation on Stream close the stream and underlying...
What language shall they sing in?
Why is it that Bernie Sanders is always called a "socialist"?
Cat is tipping over bed-side lamps during the night
Boss asked me to sign a resignation paper without a date on it along with my new contract
Non-Cancer terminal illness that can affect young (age 10-13) girls?
Why is Agricola named as such?
Square Root Distance from Integers
Nuance between philia and mania?
Why did the villain in the first Men in Black movie care about Earth's Cockroaches?
Why avoid shared user accounts?
Why did Luke use his left hand to shoot?
How do you voice extended chords?
Eww, those bytes are gross
Can polar coordinate cause misalignment in TikZ?
What game did these black and yellow dice come from?
Is there any risk in sharing info about technologies and products we use with a supplier?
Why do neural networks need so many training examples to perform?
What makes papers publishable in top-tier journals?
Translation needed for 130 years old church document
Which RAF squadrons and aircraft types took part in the bombing of Berlin on the 25th of August 1940?
Prioritising polygons in QGIS
Why didn't Tom Riddle take the presence of Fawkes and the Sorting Hat as more of a threat?
Changing the laptop's CPU. Should I reinstall Linux?
Potential client has a problematic employee I can't work with
Should I always close BufferedReader?
Does collect operation on Stream close the stream and underlying resources?Does a finally block always get executed in Java?What is a serialVersionUID and why should I use it?Efficiency of Java “Double Brace Initialization”?BufferedReader not stating 'ready' when it shouldConvert InputStream to BufferedReaderIs it necessary to close an InputStreamReader in a BufferedReaderBufferedReader - Does it take in the entire document?BufferedReader Doesn't Read All Of My Text FileReading a JSON file twice with BufferedReaderBufferedReader Deadlock: How to properly shutdown a BufferedReader
Here is a line reading a file into a List:
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());
Is this correct or should I assign the BufferedReader to a variable to be able to close it later?
java bufferedreader
|
show 2 more comments
Here is a line reading a file into a List:
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());
Is this correct or should I assign the BufferedReader to a variable to be able to close it later?
java bufferedreader
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago
|
show 2 more comments
Here is a line reading a file into a List:
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());
Is this correct or should I assign the BufferedReader to a variable to be able to close it later?
java bufferedreader
Here is a line reading a file into a List:
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))
.lines()
.collect(Collectors.toList());
Is this correct or should I assign the BufferedReader to a variable to be able to close it later?
java bufferedreader
java bufferedreader
edited 2 hours ago
Mad Physicist
37.9k1674106
37.9k1674106
asked 2 hours ago
EkaterinaEkaterina
12718
12718
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago
|
show 2 more comments
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago
|
show 2 more comments
4 Answers
4
active
oldest
votes
Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)
is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
add a comment |
You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
lines = reader.lines().collect(Collectors.toList());
}
add a comment |
Wrong answer - Streams must be closed too.
One should alway close, which can be done with try-with-resources.
--However here a Stream<String> is run to its final collect, hence everything is closed.--
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName),
StandardCharsets.UTF_8))
.lines()
.collect(Collectors.toList());
Or:
try {
URL url = classLoader.getResource(fileName);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path); // Default UTF-8.
Files.lines(path).forEach(System.out::println);
} catch (URISyntaxException e) {
...
}
A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
Could you please post a link which shows thatcollect()closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".
– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
@FlorianAlbrecht point taken. Notice thatFiles.linescloses the stream on exception and by adding an.onClosecallback for closing.
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
add a comment |
I stand corrected
From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54888904%2fshould-i-always-close-bufferedreader%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)
is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
add a comment |
Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)
is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
add a comment |
Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)
is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
Well, in your concrete example, the stream opened by
classLoader.getResourceAsStream(fileName)
is never closed. This stream must be closed - it is most likely a file handle in the local system. You can close it by closing the BufferedReader, which closes the wrapped InputStreamReader, which closes the underlying InputStream. You could instead also store a reference to the original InputStream and only close this.
Please also have a look into try-with-resources, this could potentially make things easier for you here.
answered 2 hours ago
Florian AlbrechtFlorian Albrecht
1,6051418
1,6051418
add a comment |
add a comment |
You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
lines = reader.lines().collect(Collectors.toList());
}
add a comment |
You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
lines = reader.lines().collect(Collectors.toList());
}
add a comment |
You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
lines = reader.lines().collect(Collectors.toList());
}
You should always close your resources. Closing may not be a big problem for small programs which only use a couple of files quickly, since most mature OSes will close the files for you when the process completes. However, there are usually limits on how many files you can have open at one time. It is good to be tidy, so that you don't hit those limits when you start writing bigger programs. There are also other types of resources, like network and serial ports, which you may want to let others use once your program is done with them, even if it is still running.
An alternative to closing the file manually is using try-with-resources syntax, which ensures that the file will be closed properly even in case of an error:
List<String> lines;
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {
lines = reader.lines().collect(Collectors.toList());
}
answered 2 hours ago
Mad PhysicistMad Physicist
37.9k1674106
37.9k1674106
add a comment |
add a comment |
Wrong answer - Streams must be closed too.
One should alway close, which can be done with try-with-resources.
--However here a Stream<String> is run to its final collect, hence everything is closed.--
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName),
StandardCharsets.UTF_8))
.lines()
.collect(Collectors.toList());
Or:
try {
URL url = classLoader.getResource(fileName);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path); // Default UTF-8.
Files.lines(path).forEach(System.out::println);
} catch (URISyntaxException e) {
...
}
A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
Could you please post a link which shows thatcollect()closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".
– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
@FlorianAlbrecht point taken. Notice thatFiles.linescloses the stream on exception and by adding an.onClosecallback for closing.
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
add a comment |
Wrong answer - Streams must be closed too.
One should alway close, which can be done with try-with-resources.
--However here a Stream<String> is run to its final collect, hence everything is closed.--
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName),
StandardCharsets.UTF_8))
.lines()
.collect(Collectors.toList());
Or:
try {
URL url = classLoader.getResource(fileName);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path); // Default UTF-8.
Files.lines(path).forEach(System.out::println);
} catch (URISyntaxException e) {
...
}
A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
Could you please post a link which shows thatcollect()closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".
– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
@FlorianAlbrecht point taken. Notice thatFiles.linescloses the stream on exception and by adding an.onClosecallback for closing.
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
add a comment |
Wrong answer - Streams must be closed too.
One should alway close, which can be done with try-with-resources.
--However here a Stream<String> is run to its final collect, hence everything is closed.--
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName),
StandardCharsets.UTF_8))
.lines()
.collect(Collectors.toList());
Or:
try {
URL url = classLoader.getResource(fileName);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path); // Default UTF-8.
Files.lines(path).forEach(System.out::println);
} catch (URISyntaxException e) {
...
}
A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.
Wrong answer - Streams must be closed too.
One should alway close, which can be done with try-with-resources.
--However here a Stream<String> is run to its final collect, hence everything is closed.--
List<String> lines =
new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream(fileName),
StandardCharsets.UTF_8))
.lines()
.collect(Collectors.toList());
Or:
try {
URL url = classLoader.getResource(fileName);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path); // Default UTF-8.
Files.lines(path).forEach(System.out::println);
} catch (URISyntaxException e) {
...
}
A minor point is to provide a Charset, otherwise the default platform charset is used, which varies and hence makes the code not portable, especially as the resource is of fixed and known charset.
edited 2 hours ago
answered 2 hours ago
Joop EggenJoop Eggen
77.6k755103
77.6k755103
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
Could you please post a link which shows thatcollect()closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".
– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
@FlorianAlbrecht point taken. Notice thatFiles.linescloses the stream on exception and by adding an.onClosecallback for closing.
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
add a comment |
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
Could you please post a link which shows thatcollect()closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".
– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
@FlorianAlbrecht point taken. Notice thatFiles.linescloses the stream on exception and by adding an.onClosecallback for closing.
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
Bravo @Joop Eggen . Just try-with-ressources ( mentioned above ) is a bit different than try-catch here but behind logic is neatly the same... :-)
– MS90
2 hours ago
2
2
Could you please post a link which shows that
collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".– Florian Albrecht
2 hours ago
Could you please post a link which shows that
collect() closes the stream? docs.oracle.com/javase/9/docs/api/java/io/… states that the state of the reader after terminal operation is undefined, which does not necessarily include "closed".– Florian Albrecht
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
Take this trivial code: Files.lines(path).filter(x -> x.charAt(0) != '#').collect(Collectors.toList()); – seems perfectly fair, right? Nope, that's a resource leak: If there's a blank line in the input file, the filter will throw an exception (IndexOutOfBoundsException), and thus, resource leak. Don't rely on the collector to clean up your resources.
– rzwitserloot
2 hours ago
1
1
@FlorianAlbrecht point taken. Notice that
Files.lines closes the stream on exception and by adding an .onClose callback for closing.– Joop Eggen
2 hours ago
@FlorianAlbrecht point taken. Notice that
Files.lines closes the stream on exception and by adding an .onClose callback for closing.– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
To all: Files.lines works, though normally Streams must be closed - I stand corrected. I would have expected that final operations would close, as the end is reached. What else?
– Joop Eggen
2 hours ago
add a comment |
I stand corrected
From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.
add a comment |
I stand corrected
From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.
add a comment |
I stand corrected
From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.
I stand corrected
From documentation:
Streams have a close() method and implement AutoCloseable interface, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel, for example a BufferedReader.lines will require closing.
Most streams are backed by collections, arrays, or generating functions, which require no special resource management. If a stream does require closing, it can be declared as a resource in a try-with-resources statement.
answered 1 hour ago
MS90MS90
45710
45710
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54888904%2fshould-i-always-close-bufferedreader%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
@MS90 - based on what? The documentation does not specify that the resource is closed.
– RealSkeptic
2 hours ago
@MS90 That has nothing to do with closing the resource. It's all accumulated - right. It's not closed.
– RealSkeptic
2 hours ago
This seems to imply close is not called by collect.
– TiiJ7
2 hours ago
@rkosegi Yes it reads everything in memory and closes it before looping.
– MS90
2 hours ago
@rkosegi you're mistaken; readAllLines DOES call close (via the try-with-resources construct)
– rzwitserloot
2 hours ago