文件处理案例:
以下代码打开了一个文件,但在使用完后没有去关闭这个文件
public int processFile(String fileName) throws IOException, FileNotFoundException { FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } return 1; }
请给出可能的修改方案,以便相关的文件资源使用后能够正常地关闭及回收。
方案1:
为了释放文件资源,以便相关的文件资源使用后能够正常地关闭及回收,
释放所有请求的资源,不管任何可能异常发生,即使’ bufRead ’也可能导致异常。
FileInputStream 对象也按请求关闭。
try { final FileInputStream stream = new FileInputStream(fileName); try { final BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // forward to handler } } } } catch (IOException e) { // forward to handler }
方案2:使用Java S7:try-with-resources
使用 try-with-resources 语句, 在 Java SE 7中介绍的, 释放所有获取的资源,不管任何可能发生的异常.
try (FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } catch (IOException e) { // forward to handler }
try-with-resources构建发送任何IOException的catch子句,它被转发到一个异常处理程序。这包括资源的分配过程中产生异常(即的FileInputStream或BufferedReader创建)。它还包括任何IOException异常抛出的while循环执行过程中。最后,它包括关闭bufread或流中产生任何IOException。