相关疑难解决方法(0)

我是否正确使用Java 7 try-with-resources

我期待缓存的读取器和文件读取器关闭,如果异常抛出则释放资源.

public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
    try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
    {
        return read(br);
    } 
}
Run Code Online (Sandbox Code Playgroud)

但是,是否需要有catch成功关闭的条款?

编辑:

从本质上讲,Java 7中的上述代码与Java 6中的代码相同:

public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{

    BufferedReader br = null;

    try
    {
        br = new BufferedReader(new FileReader(filePath));

        return read(br);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        try
        {
            if (br != null) br.close();
        }
        catch(Exception ex)
        {
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

java-7 try-with-resources

86
推荐指数
2
解决办法
6万
查看次数

标签 统计

java-7 ×1

try-with-resources ×1