【IO流】12 - 字节输出流 - IO异常的处理

 

package cn.itcast.io.c.bytestream.write;

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

public class FileOutputStreamDemo3 {

    /**
     * @param args
     * @throws FileNotFoundException
     */
    public static void main(String[] args) {

        File file = new File("k:\\file.txt");
        FileOutputStream fos = null;        //在外面定义好流的引用
        try {
            fos = new FileOutputStream(file);//在外面定义好流的引用,在try里面进行流对象的初始化,否则引发异常,因为file有可能就会出现异常
            fos.write("abcde".getBytes());

        } catch (IOException e) {
            System.out.println(e.toString() + "----");
        } finally {
            if (fos != null) {              //启动流,写入,关闭是正常步骤;启动流,写入失败,需要关闭;启动流失败就不需要关闭,所以这步判断启动是否失败
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException("");
                }
            }

        }

    }

}

 

posted @ 2018-01-30 00:13  清风拂柳  阅读(169)  评论(0编辑  收藏  举报