1 package 加入异常处理的字节流操作; 2 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 7 /* 8 * 加入异常处理的字节流操作 9 */ 10 public class OutpurDemo { 11 public static void main(String[] args) { 12 13 FileOutputStream fos = null; // 如果后面不能初始化则会导致空指针异常 14 try { 15 fos = new FileOutputStream("h\\fos.txt"); 16 fos.write(("java").getBytes()); 17 } catch (FileNotFoundException e) { 18 e.printStackTrace(); // 捕获文件对象不能成功创建的异常 19 } catch (IOException e) { 20 e.printStackTrace(); // 在写文件的时候会有IO异常 21 } finally { 22 // 为了保证close一定执行就放进finally里面 23 // 如果fos不是null才需要close 24 if (fos != null) { 25 try { 26 fos.close(); 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } 31 } 32 } 33 }
原文:http://www.cnblogs.com/fuck1/p/5322312.html