用字節流讀寫文件

一:IO流分類

1)按流向分:輸入流和輸出流

2)按數據類型:字節流:可以是一切文件,如純文本、圖片、音樂、視頻等

  字符流:只能是純文本文件

3)按功能分:節點:包裹源頭

      處理:增強功能,提供性能

二:字節流(重點)、字符流與文件

1).字節流:輸入流:InputStream read(byte[] b) read(byte[] b, int off, int len) close()

如果是文件操作實現類就是FileInputStream,其他操作換用其他實現類就是了。

         輸出流:OutputStream write(byte[] b) write(byte[] b, int off, int len) close() flush()

如果是文件操作實現類就是FileOutputStream,其他操作換用其他實現類就是了。

2)字符流:輸入流:Reader read(char[] cbuf) read(char[] cbuf, int off, int len) close()

如果是文件操作實現類就是FileReader,其他操作換用其他實現類就是了。

    輸出流:Writer write(char[] cbuf) write(char[] cbuf, int off, int len) close() flush()

如果是文件操作實現類就是FileWriter,其他操作換用其他實現類就是了。

三:操作流程:

1)建立聯繫

2)選擇流

3)操作

4)釋放資源  


四:讀取文件內容:

public static void main(String[] args) {

		// 1.建立聯繫
		File src = new File("F:/1.txt");
		// 2.選擇流
		FileInputStream input = null;// 提升作用域
		try {
			// 3.操作
			input = new FileInputStream(src);
			byte[] data = new byte[100];// 建立緩衝數組,數組長度可變
			int len = 0;// 讀出的實際長度
			while ((len = input.read(data)) != -1) {// 不斷讀取文件內容
				String info = new String(data, 0, len);// 字節數組轉換成字符串
				System.out.println(info);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("讀取文件失敗");
		} finally {
			// 4.釋放資源
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("關閉輸入流失敗");
				}
			}
		}
	}

五:往文件中寫入內容:

public static void main(String[] args) {
		// 1.建立聯繫
		File src = new File("F:/1.txt");
		// 2.選擇流
		FileOutputStream out = null;// 提升作用域
		try {
			out = new FileOutputStream(src, true);// 爲true時表示銜接到文件中,爲false或者沒有時表示覆蓋源文件內容
			// 3.操作
			String str = "I must study hard\r\n";// \r\n相當於Enter鍵-->換行符
			byte[] data = str.getBytes();// 將字符串轉換成字節數組
			out.write(data);
			out.flush();// 強制沖刷出去
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("文件未找到");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件寫入異常");
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println("文件輸出流關閉失敗");
				}
			}
		}
	}


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