java - 如何使用 Java7 try-with-resources 特性将资源作为参数传递

标签 java try-catch java-7 try-with-resources

我看过java7 try-with-resources .如果可关闭资源作为参数,我们不需要声明资源。对于这种情况,我们如何使用此功能?

public static void write(byte[] b, OutputStream os) throws Exception {
    try {
        os.write(b);
    }
    catch(Exception e) {
        logger.log(Level.INFO, "Exception in writing byte array");
    }
    finally {
        try {
            if(os != null) {
                os.close();
            }
        }catch(Exception e) {
            logger.log(Level.INFO, "Exception while close the outputstream");
            throw e;
        }
    }
}

最佳答案

你可以简单地写:

static void write(byte[] b, OutputStream os) throws Exception {
    try (OutputStream o = os) {
        o.write(b);
    }
}

关于java - 如何使用 Java7 try-with-resources 特性将资源作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33118347/

相关文章:

java - Selenium Actions 类无法在大于 3.1 的 selenium 版本中解析

java - Activity 转换期间的背景

java - 避免使用泛型进行不安全的转换

javascript - 这是 try/catch block 的正确使用吗

Java并发从多个线程写入单个文本文件?

java - 在 Java 中使用单个 for-each 循环遍历多个列表

java - 为什么每次调用 toOncreate 后我的计数器都会重置?

c++ - 在 C++ 中抛出和捕获自定义异常的问题

java - 嵌套 try 和 catch 是否有其他方法?

Java - 如何从时间戳集合中删除重复项?