IO流_FileOutputStream写出数据加入异常处理

来源:互联网 发布:游戏开发用什么软件 编辑:程序博客网 时间:2024/05/01 10:56
package cn.itcast_01;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;/* * 加入异常处理的字节输出流 */public class FileOutputStreamDemo4 {public static void main(String[] args) {// 分开做异常处理// FileOutputStream fos = null;// try {// fos = new FileOutputStream("fos4.txt");// } catch (FileNotFoundException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }//// try {// fos.write("java".getBytes());// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }//// try {// fos.close();// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }// 一起做异常处理// try {// FileOutputStream fos = new FileOutputStream("fos4.txt");// fos.write("java2".getBytes());// fos.close();// } catch (FileNotFoundException e) {// e.printStackTrace();// } catch (IOException e) {// e.printStackTrace();// }// 改进版// 为了在finally里能看到该对象,就必须定义到外面,为了访问不出问题,还必须给出初始化值FileOutputStream fos = null;try {// fos = new FileOutputStream("z:\\fos4.txt");fos = new FileOutputStream("fos4.txt");fos.write("java3".getBytes());} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 如果fos不为null,才需要close()if (fos != null) {// 为了保证close()一定会执行,就放到这里了try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}}

0 0
原创粉丝点击