Reputation:
I am working with Files in java and my IDE is VS-Code.The problem I am facing that it is showing the following as warnings alongwith a bunch of others-
Resource leak: 'sc' is never closed
Resource leak: 'scan' is never closed
where "sc" is defined as -
Scanner sc = new Scanner(System.in);
and "scan" as -
File fobj=new File("Marks.txt");
Scanner scan = new Scanner(fobj);
I am asking that Using @SuppressWarnings("resources")
only blocks warning from Scanner object sc.Is there any way to block all of these open resources warnings which can be defined at the beginning of the Java file because I have to include @SuppressWarnings("resources") in every class I write.
Upvotes: 0
Views: 1670
Reputation: 140319
You can add suppressions to the containing class:
@SuppressWarnings("resources")
class YourClass {
// ...
}
and this will suppress all resources warnings in the class.
This isn't such a great idea, though, because it will also suppress warnings about resources you do want to close, like scan
.
I would say you've got a deeper problem if you're worried about adding suppressions in all the places where the warnings occur, because this implies you've got warnings in a lot of places.
In terms of suppressing the warning just on the Scanner sc = new Scanner(System.in);
: you should only be creating a single scanner on a stream, and, as such, you should only need to add the suppression in one place.
If you're creating multiple scanners on System.in
, you may get unexpected results from them, consider each scanner may consume part of the input stream. A better approach is to construct one scanner (on a given stream), and pass it around.
For Scanner scan
, a better approach than suppressing the warning would be just to close the stream, so there is no warning to suppress. Try-with-resources guarantees this:
File fobj=new File("Marks.txt");
try (Scanner scan = new Scanner(fobj)) {
// ... Do stuff with scan.
}
// And now it's guaranteed to be closed.
Note that you can use try-with-resources around new Scanner(System.in)
, and it is guaranteed to be closed - but you shouldn't. Closing the Scanner
closes the underlying stream - System.in
.
You should only close streams that your code opened directly - your code didn't open System.in
, the JVM did. System.in
can't be reopened once closed, so you could accidentally break other parts of your code which assumed it would be open.
It's gross that you have to consider System.in
and "other" streams separately - the "helpful" closing of child streams in Scanner
(etc) is behavior that predates the try-with-resources syntax, so it's just something Java is stuck with.
Upvotes: 1