I/O流類精練一題——利用FileInputStream 和FileOutputStream,完成下面的要求: 用FileOutputStream 在當前.......

利用FileInputStream 和FileOutputStream,完成下面的要求:
1) 用FileOutputStream 在當前目錄下創建一個文件“test.txt”,並向文件輸出“Hello
World”,如果文件已存在,則在原有文件內容後面追加。
2) 用FileInputStream 讀入test.txt 文件,並在控制檯上打印出test.txt 中的內容。
3) 要求用try-catch-finally 處理異常,並且關閉流應放在finally 塊中。

import java.io.*;
public class Text_1 {
		public static void main(String[] args)  {
			FileOutputStream file = null;
			FileInputStream in =null ;
			try {
				file = new FileOutputStream("c:\\javas\\kk\\text.txt");
				String str = "Hello World" ;
				byte []b = str.getBytes();//得到字節數組
				try {
					file.write(b);
				} catch (IOException e) {
					// TODO 自動生成的 catch 塊
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
			try {
				in = new FileInputStream("c:\\javas\\kk\\text.txt");
				byte []b = new byte [1024] ;
				try {
					int k = in.read(b);
					System.out.println(new String(b,0,k));
				} catch (IOException e) {
					// TODO 自動生成的 catch 塊
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}finally {
				try {
					file.close();
					in.close();
				} catch (IOException e) {
					// TODO 自動生成的 catch 塊
					e.printStackTrace();
				}
			}
		}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章