Construction. try-with-resources

[comp1110-97]

Opening a file reserves resources on your computer. Conflicts over such resources may arise when multiple programs try to access the resources at the same time. Additionally, not every operation on such resources will necessarily happen immediately. For example, reading from and writing to files is somewhat expensive, so we use something like BufferedReader and (coming up) BufferedWriter, which try to combine several smaller operations into bigger ones, meaning that a number of smaller writes will not immediately take effect until there are enough of them. If your program crashes in the meantime, it is likely that such data will be lost. Closing an open file forces any remaining data to be written and any required resources to be returned to the operating system.

Therefore, it is a good idea to keep things clean and tidy, and close an open file as soon as you do not need it anymore (at least for the time being - you can always reopen it later). All readers and writers have a close() method to do just that. However, given that lots of exceptions can happen when interacting with files, guaranteeing that the file will be closed regardless of what happens can be tricky. By default, this is what the finally block of the try-catch-finally construct is for:

try { FileReader fr = new FileReader(theFile); try { BufferedReader reader = new BufferedReader(fr); // use the reader } finally { if(reader != null) { reader.close(); } } } catch(IOException e) { // handle IOException } finally { if(fr != null) { fr.close(); } }

Since this is a very standard pattern, a variant of try-catch-finally, called "try-with-resources", makes this more concise:

try(FileReader fr = new FileReader(theFile); BufferedReader reader = new BufferedReader(fr)) { // use the reader } catch(IOException e) { // handle IOException }

In this case, the BufferedReader and the FileReader will automatically be close in that order (reversed order of declaration) whenever program execution leaves the try-with-resources block. The two code blocks here are not perfectly equivalent because the ordering of closing the reader and handling the IOException is different, but that typically does not really matter.

bars magnifying-glass caret-down plus minus arrow-right xmark