目录

Life in Flow

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

X

IO流异常处理

JDK6

 1/**
 2     * try{}catch{}finally{释放资源}
 3     *
 4     * @throws IOException
 5     */
 6    @Test
 7    public void tryCatchTesting2() throws IOException {
 8        BufferedInputStream bis = null;
 9        BufferedOutputStream bos = null;
10
11        try {
12            FileInputStream inputStream = new FileInputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\1.txt");
13            bis = new BufferedInputStream(inputStream);
14
15            FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Ryzen-7-3800X\\Pictures\\Camera Roll\\test\\1\\222.txt");
16            bos = new BufferedOutputStream(outputStream);
17
18            int size;
19            byte[] buf = new byte[1024];
20
21            while ((size = bis.read(buf)) != -1) {
22                bos.write(buf, 0, size);
23            }
24        } catch (FileNotFoundException e) {
25            e.printStackTrace();
26        } finally {
27            if (bis != null) {
28                try {
29                    bis.close();
30                } catch (Exception e) {
31                    e.printStackTrace();
32                } finally {
33                    if (bos != null) {
34                        try {
35                            bos.close();
36                        } catch (Exception e) {
37                            e.printStackTrace();
38                        }
39                    }
40                }
41            }
42        }
43    }

JDK7

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

作者:Soulboy