A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 鲤鱼仙 中级黑马   /  2015-7-9 21:22  /  388 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

import java.io.*;

public class IOStreamException {
        public static void main(String[] args) {
                // 提升变量的作用范围
                // try外声明变量,try内,建立对象
                FileOutputStream fos = null;
                FileOutputStream fos1 = null;
                try {
                        // 创建字节输出流子类对象
                        fos = new FileOutputStream("c:\\a.txt");
                        fos1 = new FileOutputStream("c:\\a1.txt");
                        fos.write(97);
                        fos1.write(98);
                } catch (IOException ex) {
                        // IO异常特殊,写文件,不要处理,让程序停止下来
                        ex.printStackTrace();
                        // 抛出运行时期异常
                        throw new RuntimeException("文件写入失败");
                } finally {
                        try {
                                // 对变量fos进行非空判断,防止空指针异常
                                if (fos != null)
                                        fos.close();
                        } catch (IOException ex) {
                                throw new RuntimeException("关闭资源失败");
                        } finally {
                                try {
                                        if (fos1 != null)
                                                fos1.close();
                                } catch (IOException ex) {
                                        throw new RuntimeException("关闭资源失败");
                                }
                        }
                }
        }
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马