Java Scanner question

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
I guess this question could apply to any of the input/output streams.

If i have a Scanner or some other stream and it is local to a say a while loop, will it close by itself when the while loop ceases to function?
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
All Input and Output streams need to have the close method called. Close will call flush if needed but its imperative that you do this or you'll leak native resources. The standard pattern for this is:

XXXStream s = null
try {
s = new XXXStream(...);
//read/write stream etc
} finally {
if(s!=null) {
try {
s.close()
} catch(IOException e){}
}
}

Ugly but necessary or it will come back to bite you.
 

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
I see, so if i have Scanner aScanner = new Scanner(etcetc) and its declared in a while loop I would need to have aScanner.close() as the last line within the loop and it would close the stream upon each execution of the loop?

Would it be better if I declared the Scanner outside the loop like this:

Scanner aScanner = null;
while (arguement)
{
aScanner = new Scanner(etcetc)
}

try
{
aScanner.close()
}
catch
{
etc
}


as opposed to this where close() is called every single looping:

while (arguement)
{
Scanner aScanner = new Scanner(etcetc)
try
{
aScanner.close();
}
catch
{
etc
}
}
 

BrightCandle

Diamond Member
Mar 15, 2007
4,762
0
76
For every scanner you make you need to call close. The first example of code will only close the last scanner in the loop, and hence you'll leak OS resources for the other scanners that were not closed. The second one is better in the sense it attempts to close each scanner but it wont catch all possibilities of failure and hence still has potential to leak resources. Stick to the pattern and do so more in the second style than the first.