Prefer try-with-resources to try-finally

Demo1(Read the second line)
finally和try裏如果同時拋出異常,try裏面的異常不會顯示在異常堆棧裏,會影響debug。

static void readFirstLineOfFile(String path) throws IOException {
        BufferedReader bufferedReader
                = new BufferedReader(new FileReader(path));
        try{
            bufferedReader.readLine();
            System.out.println(bufferedReader.readLine());
        }finally {
            bufferedReader.close();
        }
    }

Demo2(Copy)
需要關閉的資源多了,用try-with有點傻

static void copy(String src, String dst) throws IOException {
        FileInputStream in = new FileInputStream(src);
        try{
            FileOutputStream out = new FileOutputStream(dst);
            try{
                byte[] b = new byte[100];
                int n = 0;
                while( 0<=(n = in.read(b))){
                    out.write(b, 0, n);
                }
            }finally{
                out.close();
            }
        }finally {
            in.close();
        }
    }

Demo3(New-Read the second line)
使用try-resources會自動執行close方法,這樣可讀性更高。AutoCloseable接口需要被實現。

static void readFirstLineOfFileNew(String path) throws IOException {
        try(BufferedReader bufferedReader
                    = new BufferedReader(new FileReader(path))){
            bufferedReader.readLine();
            System.out.println(bufferedReader.readLine());
        }
    }

Demo4
使用了try-with-resources

static void copy2(String src, String dst) throws IOException {
        try(FileInputStream in = new FileInputStream(src);
            FileOutputStream out = new FileOutputStream(dst);
        ) {
            byte[] b = new byte[100];
            int n = 0;
            while( 0<=(n = in.read(b))){
                out.write(b, 0, n);
            }
        }
    }

test unit

    public static void main(String[] args) throws IOException {
//        Item9.readFirstLineOfFile("c:/work/a.txt");
//        Item9.copy("c:/work/a.txt", "c:/work/b.txt");
//        Item9.readFirstLineOfFileNew("c:/work/a.txt");
        Item9.copy2("c:/work/a.txt", "c:/work/c1.txt");
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章