Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with opening and closing a stream like this?

Tags:

java

try-catch

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");
         }
    }
like image 966
BURNS Avatar asked Jan 28 '14 09:01

BURNS


People also ask

How do you close streams?

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.

What happens if stream is not closed Java?

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.

What is the method used as an alternate for the Close method which automatically writes unto a file?

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.


1 Answers

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.

like image 194
Tim B Avatar answered Oct 09 '22 04:10

Tim B