So I wrote some code and Netbeans suggests convert to try-with-resources on the same line I instantiate sc . This suggestion pops up the moment I put the sc.close() after the while-loop. I don't quite understand why this close-operation is badly placed.
public static void main(String[] args) {
try{
Scanner sc = new Scanner(new File(args[0]));
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
sc.close();
} catch(FileNotFoundException e){
System.out.println("Het bestand kon niet gevonden worden.");
} catch(Exception e){
System.out.println("Onbekende Fout");
}
}
Streams have a BaseStream. close() method and implement AutoCloseable , but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset) ) will require closing.
IO Resources. Under the hood, this method opens a FileChannel instance and then closes it upon stream closure. Therefore, if we forget to close the stream, the underlying channel will remain open and then we would end up with a resource leak.
When you call close() the Buffer flushes into the file. You can also call flush() for forcing the data to be written without closing the stream.
The problem is that if anything inbetween the open and the close returns from the method or throws an exception then the close doesn't get called.
Using a try-with-resources (or pre Java 7 try-finally) to do the close guarantees that the stream gets closed every single time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With