目录

Life in Flow

知不知,尚矣;不知知,病矣。
不知不知,殆矣。

X

IO流异常处理

JDK6

/**
     * try{}catch{}finally{释放资源}
     *
     * @throws IOException
     */
    @Test
    public void tryCatchTesting2() throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            FileInputStream inputStream = new FileInputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\1.txt");
            bis = new BufferedInputStream(inputStream);

            FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\222.txt");
            bos = new BufferedOutputStream(outputStream);

            int size;
            byte[] buf = new byte[1024];

            while ((size = bis.read(buf)) != -1) {
                bos.write(buf, 0, size);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bos != null) {
                        try {
                            bos.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

JDK7

/**
     * JDK7之后的写法,JDK9⼜进⾏了改良,但是变化不⼤,记住下⾯的写法即可
     * 需要关闭的资源只要实现了java.lang.AutoCloseable,就可以⾃动被关闭
     * try()⾥⾯可以定义多个资源,它们的关闭顺序是最后在try()定义的资源先关闭。
     *
     * @throws IOException
     */
    @Test
    public void tryCatchTesting3() throws IOException {
        try (FileInputStream inputStream = new FileInputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\1.txt");
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\222.txt");
             BufferedOutputStream bos = new BufferedOutputStream(outputStream);
        ){
            int size;
            byte[] buf = new byte[1024];
            
            while ((size = bis.read(buf)) != -1) {
                bos.write(buf, 0, size);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

作者:Soulboy