天天看點

try-with-resource 關閉 io流

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()方法,整個代碼也會簡潔不少.

如果有多個需要關閉的類, 直接在()中聲明類然後利用分号隔開就可以.