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("关闭资源失败");
}
}
}
}
}
|
|