Java中IO流标准异常处理代码

  • 1.7版本之前
    private static void Demo_05() throws IOException{
    
    
        FileOutputStream fout = new FileOutputStream("bbb.txt");
        String s = "你好世界";
        fout.write(s.getBytes());
        fout.close();
        //标准异常处理代码
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
    
    
            fis = new FileInputStream("bbb.txt");
            fos = new FileOutputStream("copy_bbb.txt");
            byte[] arr = new byte[4];
            int length;
            while ((length = fis.read(arr)) != -1) {
    
    
                fos.write(arr, 0, length);
            }
        }finally {
    
    
            try{
    
    
                if(fis != null) fis.close();
            }finally {
    
    
                if(fos != null) fos.close();
            }
        }
    }

  • 1.7版本
    private static void Demo_06() throws IOException{
    
    
        FileOutputStream fout = new FileOutputStream("bbb.txt");
        String s = "你好世界";
        fout.write(s.getBytes());
        fout.close();
        //标准异常处理代码
        try(FileInputStream fis = new FileInputStream("bbb.txt");
            FileOutputStream fos = new FileOutputStream("copy_bbb.txt");){
    
    
            byte[] arr = new byte[4];
            int length;
            while ((length = fis.read(arr)) != -1) {
    
    
                fos.write(arr, 0, length);
            }
        }
    }

1.7版本,IO流放在小括号()里面,会自动调用close方法

详细请见底层代码

猜你喜欢

转载自blog.csdn.net/younow22/article/details/113387430