I'm using constructor chaining, and I'm worried that it's causing a resource leak. Here are my two constructors:
/**
* Constructor to build the map based off of a file. Redirects to the Scanner-based constructor
* @param fileName the name of the file to open
*/
public GeoMap(String fileName) throws FileNotFoundException {
this(new Scanner(new File(fileName)));
}
/**
* Constructor to build the map based off of a Scanner. (Probably from an open file.)
* @param scanner the Scanner to read
*/
public GeoMap(Scanner scanner) {
// goes on to read the string data and make an object...
It's important that the object be created from any type of Scanner
(keyboard, file, etc.), though it'll usually be from a file. The problem is that I think there's a resource leak going on here. Whenever I'm reading a file, I like to close it when I'm done. Problem is, the constructor chaining means that the this()
call must be the first line. I'd be inclined to do something like this:
this(Scanner scannerToClose = new Scanner(new File(fileName)));
In my mind that would give me the name of a Scanner
I could then close out. But that seems to really confuse the compiler--I get about 5 compile-time errors out of it, including a lot of "cannot find symbol" problems that imply that the compiler's just not wired for this sort of thing. Does Java support this? Or do I need to make a totally different initFromScanner()
function that both constructors call? (Not elegant.)
Thanks.
Call scanner.close() at the end of your GeoMap(Scanner scanner) constructor.
This will close the Scanner created in GeoMap(String filename) since a reference to it is passed into the GeoMap(Scanner scanner) as scanner.
In essence, the scanner variable points to the new scanner that was created, so calling scanner.close() anywhere, in any method, closes it for any and all other methods it may be in the scope of.
Here is a program which demonstrates the object oriented nature of Scanners:
input.txt:
Smitty
output:
In essence it doesn't matter where the Scanner is created, if it is closed at any point, it is closed everywhere that it is in scope.