This is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class temp
What is giving you this warning? Presumably it warns because the allocation/closing isn't done in a try/finally block, which generally is a bad idea (in this specific case not a problem though because the only thing that can throw an error is the new FileReader and if it throws no resource was actually allocated - but that can change with a single method call..)
Closing a scanner closes the underlying stream (to be exact anything that implements itself Closeable
(yes BufferedReader
does) so the code is fine apart from that.
Yes, your code has a potential (but not real) memory leak. You assign the return value of useDelimiter(a)
to the local variable scanner
, but the constructor result is thrown away. That is why you get the warning.
In practice, the return value of useDelimiter(a)
is exactly the same object as the one returned from the constructor call, so your code closes the resource just fine. But this is something the compiler/code analysis tool cannot detect as it would have to know the useDelimiters implementation for that.
And a really good code analysis tool should have shown you an additional warning, because you are closing a resource which has not been opened in this method (the return value of useDelimiter). If you had those 2 messages together, the symptoms might have been more clear to you.
If you split the code like this, will the warning go away?
Scanner scanner = new Scanner(a);
scanner.useDelimiter(",");
scanner.close();
Have you try :
Scanner scanner = new Scanner(new BufferedReader(new FileReader("a"))).useDelimiter(",");
If it does not work you have to add a.close();