try-with-resources

Am I using the Java 7 try-with-resources correctly

一世执手 提交于 2019-11-26 06:28:11
问题 I am expecting the buffered reader and file reader to close and the resources released if the exception is throw. public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException { try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { return read(br); } } However, is there a requirement to have a catch clause for successful closure? EDIT: Essentially, is the above code in Java 7 equivalent to the below for Java 6: public static Object[] fromFile

Correct idiom for managing multiple chained resources in try-with-resources block?

依然范特西╮ 提交于 2019-11-26 06:13:39
问题 The Java 7 try-with-resources syntax (also known as ARM block ( Automatic Resource Management )) is nice, short and straightforward when using only one AutoCloseable resource. However, I am not sure what is the correct idiom when I need to declare multiple resources that are dependent on each other, for example a FileWriter and a BufferedWriter that wraps it. Of course, this question concerns any case when some AutoCloseable resources are wrapped, not only these two specific classes. I came

Try With Resources vs Try-Catch

Deadly 提交于 2019-11-26 05:53:57
问题 I have been looking at code and I have seen try with resources. I have used the standard try-catch statement before and it looks like they do the same thing. So my question is Try With Resources vs Try-Catch what are the differences between those, and which is better. Here is a try with resources : objects jar = new objects(\"brand\"); objects can= new objects(\"brand\"); try (FileOutputStream outStream = new FileOutputStream(\"people.bin\")){ ObjectOutputStream stream = new

How should I use try-with-resources with JDBC?

陌路散爱 提交于 2019-11-25 23:37:11
问题 I have a method for getting users from a database with JDBC: public List<User> getUser(int userId) { String sql = \"SELECT id, name FROM users WHERE id = ?\"; List<User> users = new ArrayList<User>(); try { Connection con = DriverManager.getConnection(myConnectionURL); PreparedStatement ps = con.prepareStatement(sql); ps.setInt(1, userId); ResultSet rs = ps.executeQuery(); while(rs.next()) { users.add(new User(rs.getInt(\"id\"), rs.getString(\"name\"))); } rs.close(); ps.close(); con.close();