我期待缓存的读取器和文件读取器关闭,如果异常抛出则释放资源.
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)