1.在利用IO流的时候我们都需要关闭IO流, 比如 input.close(),一般是放在 finally 里面,但是如果多个类的话情况就会很复杂.
static void copy2(String src, String dst) { InputStream in = null; try { in = new FileInputStream(src); OutputStream out = null; try { //在打开InputStream后在打开OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) { out.write(buf, 0, n); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
一个简单的文件拷贝工作会整的很复杂,如果在有别的io流的话就会更复杂,整个代码很难懂,而且 close()方法调用的时候也会抛出异常,所以内部也需要捕获一次异常.
2.利用 try-with-resource
static void copy(String src, String dst) throws Exception, IOException { try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)){ byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) >= 0) { out.write(buf, 0, n); } } finally { } }
利用 try-with-resource ,我们直接在 try ( )中声明实现了AutoCloseable 的类,就可以在代码执行完以后自动执行 close()方法,整个代码也会简洁不少.
如果有多个需要关闭的类, 直接在()中声明类然后利用分号隔开就可以.