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 block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 如果fos不為null,才需要close() if (fos != null) { // 為了保證close()一定會執行,就放到這里了 try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
新聞熱點
疑難解答