欢迎来到萧静默的博客

书山有路勤为径,学海无涯苦作舟。

Java-IO流-流对象异常处理

package cn.bruce.IO;

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

public class IOExceptionDemo {
    public static void main(String[] args) {
        // try外面申明变量,里面建立对象
        // 细节:保证流对象的作用域足够
        // catch怎么处理异常要写清楚,输出异常信息方便查看
        // 停下程序重新尝试
        // 如果流对象建立失败,需要关闭流资源吗 实际上new失败了 不需要关闭资源
        FileOutputStream fOutputStream = null;
        try
        {
            fOutputStream = new FileOutputStream("E:\\A\\BB.txt");
            fOutputStream.write("a111aaa".getBytes());
        } catch (IOException e)
        {
            e.printStackTrace();
            throw new RuntimeException("文件写入失败,请重新尝试!");
        } finally
        {
            try
            {
                if (fOutputStream != null) //如果流对象空就关闭 
                {
                    fOutputStream.close();
                }
            } catch (IOException e2)
            {
                e2.printStackTrace();
                throw new RuntimeException("关闭资源失败,请重新尝试!");
            }

        }

    }
}

 

posted @ 2020-08-21 10:22  萧静默  阅读(230)  评论(0编辑  收藏  举报