Try-with-resources is a wonderful addition to the java language back in version 7. It allows you to let java handle closing resources quietly after the try-statement ends, regardless of whether it's statements ended successfully or not. If you're not using this, you're probably adding at least 2 more lines of code, if not more.
"Resources" that this try-statement uses is any class that implements the Closeable interface. Also, try-with-resources can be used with multiple resources in the parentheses.
Example using try-with-resources
try-with-resources with one resource:
try(CSVReader csvReader =
new CSVReader(Files.newBufferedReader(Paths.get(fileToProcess)))) { //read from the CSV file, line by line...
}
try-with-resources with multiple resources:try(BufferedReader bReader = Files.newBufferedReader(Paths.get(fileToProcess));CSVReader csvReader = new CSVReader(bReader)) {//read from the CSV file, line by line...
}
If you did a normal try-catch statement here, you'd have to add a "finally" block to close your resource, or you could have some problems with memory leaks, and something about having too many files open. :-/
Try-with-resources will suppress any exceptions thrown in the try-block, but you'll never have to remember to close your resources again!
Comments
Post a Comment