Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why is it a good practice to use close when using the scanner class ?  RSS feed

 
Vijairam Ganeshmoorthy
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does java ide  give a warning when I don't use close while using the scanner class ? Does it have any benefit ?
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is that an example of Eclipse being too clever for its own good? It is right that leaving a Scanner object open risks a resource leak, but it probably doesn't actually tell you to call its close() method. If you leave a Scanner pointing to a file open, then that file may be locked as unavailable to reading at least until the current JVM exits. So Scanners pointing to files, sockets, etc must be closed when you have finished with them, but you don't call close(). Not unless you are using an old version of Java®, that is. Since Java7 all closing of files is better done with try with resources instead.
There is an exception; you must never close Scanners or readers pointing to System.in (or something pointing to System.out/System.err). You can find out about the dire consequences of closing System.in in this old thread.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!