Tag: try with resources

为什么不用Catch或者最后写Try?

为什么在没有Catch或Finally的情况下编写Try,如下例所示? protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html;charset=UTF-8”); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println(“”); out.println(“”); out.println(“”); out.println(“Servlet tryse”); out.println(“”); out.println(“”); out.println(“Servlet tryse at ” + request.getContextPath() + “”); out.println(“”); out.println(“”); } }

java.util.concurrent.locks.Lock的AutoCloseable包装中的任何风险?

通过Java 7中引入的try-with-resource ,我惊讶地发现Lock还没有被改装为AutoCloseable 。 它似乎相当简单,所以我自己添加如下: class Lock implements AutoCloseable { private final java.util.concurrent.locks.Lock _lock; Lock(java.util.concurrent.locks.Lock lock) { _lock = lock; _lock.lock(); } @Override public void close() { _lock.unlock(); } } 这适用于AutoCloseableReentrantReadWiteLock类,用法如下: try (AutoCloseableReentrantReadWiteLock.Lock l = _lock.writeLock()) { // do something } 由于这似乎是直接和规范使用自动关闭RAII我认为必须有一个很好的理由不应该这样做。 有人知道吗?

在java中尝试使用资源和返回语句

我想知道在try-with-resources块中放置一个return语句是否会阻止资源自动关闭。 try(Connection conn = …) { return conn.createStatement().execute(“…”); } 如果我写这样的东西会关闭Connection吗? 在Oracle文档中,声明: try-with-resources语句确保在语句结束时关闭每个资源。 如果由于return语句从未到达语句的结尾会发生什么?

Stream上的收集操作是否关闭流和底层资源?

以下代码是否需要包含在try-with-resources中以确保底层文件已关闭? List rows = Files.lines(inputFilePath).collect(Collectors.toList());

使用try-with-resources静静地关闭资源

是否可以忽略使用try-with-resources语句关闭资源时抛出的exception? 例: class MyResource implements AutoCloseable{ @Override public void close() throws Exception { throw new Exception(“Could not close”); } public void read() throws Exception{ } } //this method prints an exception “Could not close” //I want to ignore it public static void test(){ try(MyResource r = new MyResource()){ r.read(); } catch (Exception e) { System.out.println(“Exception: […]

尝试使用Java 1.6中的资源

我有以下代码: public class Main { public static void main(String[] args) throws SQLException { try ( Connection conn = DBUtil.getConnection(DBType.HSQLDB); Statement stmt = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(“SELECT * FROM tours”); ) { DBUtil.getConnection(); } catch (SQLException e) { DBUtil.processException(e); } } } 我使用此代码从数据库中获取数据。 我的问题是我不允许使用Java 1.7编译器并且必须使用1.6。 如何将try-with-resources-code转换为与1.6编译器一起使用? 在这个特殊的尝试块中究竟发生了什么?