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");
    }
发布了35 篇原创文章 · 获赞 0 · 访问量 2495

猜你喜欢

转载自blog.csdn.net/greywolf5/article/details/104861196