1

I found a bit of coding here: Java: Printing from a file

Scanner fRead = new Scanner(new File(targetFileName));
while (fRead.hasNextLine())
  System.out.println(fRead.nextLine());

My questions:

  • Does creating a File object from 'file.txt' open said file?
  • If so (I'm relatively certain it would), wouldn't the snippet leave said file open?
  • What happens when said file is left open after the program terminates?

1 Answers1

2

The file will be closed eventually, when the garbage collector will do its job, but you are not sure when this will happen. The best thing to do in such cases is to interact with the scanner in a try-catch-finally construct and close it in the finally block.

try {
    scanner = new Scanner(file);
    // read contents
} catch (Exception ex) {
    // handle problems 
} finally {
    // close the scanner
    scan.close();
}

As suggested in comments, starting from java 7, it is possible to simplify the code by using the newly introduced try-with-resources construct which goes like this:

try (Scanner scanner = new Scanner(file)) {
    //read file contents 
} catch (Exception e) {
    // handle exceptions 
}

In this case you don't need to explicitly close the scanner as java will do it automatically.

NiVeR
  • 9,644
  • 4
  • 30
  • 35
  • 2
    Maybe you want also mention the try-with-resource statement as `Scanner` implements `Closeable`. – LuCio Jul 09 '18 at 18:32
  • Thank you for the suggestions, it was added. – NiVeR Jul 09 '18 at 19:07
  • Judging from a quick read on try-with-resources, you'd do something like: try (scanner = new Scanner(new File(filename))) { while (scanner.hasNextLine()) {System.out.println(scanner.nextLine())}} – japanese Harry Styles Jul 09 '18 at 19:08