Close resource quietly using try-with-resources

I found this answered on the coin-dev mailing list: http://mail.openjdk.java.net/pipermail/coin-dev/2009-April/001503.html 5. Some failures of the close method can be safely ignored (e.g., closing a file that was open for read). Does the construct provide for this? No. While this functionality seems attractive, it is not clear that it’s worth the added complexity. As a practical … Read more

Does collect operation on Stream close the stream and underlying resources?

There is a trick to make the Stream implementation calling close() after the terminal operation: List<String> rows = Stream.of(Files.lines(inputFilePath)).flatMap(s->s) .collect(Collectors.toList()); It simply creates a stream encapsulating the stream of lines as a single item and uses flatMap with an identity function (Function.identity() would work as well) to turn it into a stream of lines again. … Read more

Java 7 Automatic Resource Management JDBC (try-with-resources statement)

try(Connection con = getConnection()) { try (PreparedStatement prep = con.prepareConnection(“Update …”)) { //prep.doSomething(); //… //etc con.commit(); } catch (SQLException e) { //any other actions necessary on failure con.rollback(); //consider a re-throw, throwing a wrapping exception, etc } } According to the oracle documentation, you can combine a try-with-resources block with a regular try block. IMO, … Read more

Close multiple resources with AutoCloseable (try-with-resources)

Try with resources can be used with multiple resources by declaring them all in the parenthesis. See the documentation Relevant code excerpt from the linked documentation: public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with // try-with-resources … Read more