IO流-字节输出流OutputStream异常处理

时间:2022-04-18 04:50:49
package it.cast_01;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo1 {
    public static void main(String[] args) {
        
        /*
        try {
            fos = new FileOutputStream("fos1.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            fos.write("Hello".getBytes());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        
        //  一起如何做异常
        /*try{
            fos = new FileOutputStream("fos1.txt");
            fos.write("Hello".getBytes());
            fos.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }*/
        
        //改进版
        //
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream("fos1.txt");
            fos.write("Hello".getBytes());
            //当创建对象不成功时候,就不会执行close()方法
            //fos.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally{
            //当创建对象成功时候,在执行close()方法。
            if(fos!=null){
            try {
                fos.close();
            } catch (IOException e) {
                
                e.printStackTrace();
            }
            }
        }
        
        
    }

}