字节流写数据的异常处理演示示例

首先使用try...catch来处理

public class FileOutputStreamDemo03 {
    public static void main(String[] args) {
        try {
        //创建文件输出流以指定的名称写入文件
        FileOutputStream fos = new FileOutputStream("myFile\\fos.txt");
        //写数据
        fos.write("hello".getBytes());
        //释放资源
        fos.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

IO中最重要的步骤就是释放资源,上述代码中,假如在执行释放资源前遇到了异常,就会直接进入catch中,而无法执行到close方法,所以必须要有方法来强制执行close方法。finally

public class FileOutputStreamDemo03 {
    public static void main(String[] args) {
//        try {
//        //创建文件输出流以指定的名称写入文件
//        FileOutputStream fos = new FileOutputStream("myFile\\fos.txt");
//        //写数据
//        fos.write("hello".getBytes());
//        //释放资源
//        fos.close();
//        } catch (IOException e){
//            e.printStackTrace();
//        }
        FileOutputStream fos = null;
        try {
            //创建文件输出流以指定的名称写入文件
            fos = new FileOutputStream("myFile\\fos.txt");
            //写数据
            fos.write("hello".getBytes());
            //释放资源
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @ 2020-04-15 10:51  硬盘红了  阅读(185)  评论(0)    收藏  举报