IO流(三)字符流(讀寫字符,並可以設置字符類型比如UTF-8)

字符輸出 流  OutputStreamWriter,也是基於字節流FileOutputStream

  • BufferedWriter  好處:  newLine()  寫入一個行分隔符。 
    • FileWriter 寫文件,可追加而不是重新覆蓋 專門針對文件寫入,可以追加內容append()(普通輸出流寫文件是刪除文件原本內容重新從頭開始寫) 
void writeFile() throws IOException {
		File file = new File("f://d.txt");
		FileOutputStream fos = new FileOutputStream(file);
		OutputStreamWriter osw = new OutputStreamWriter(fos);//

		osw.write("hello,i am cuijiao");
		osw.write(99);

		osw.close();
		fos.close();
	}

字符輸出 流  InputStreamReader,也是基於字節流FileInputStream

  • BufferedReader 好處 readLine()  讀取一個文本行。 
    • FileReader 專門針對文件讀(通常來講,流不僅針對文件,網絡間的數據傳輸也是通過流) 
void readFile() throws IOException {
		File file = new File("f://d.txt");
		if (!file.exists()) {
			return;
		}
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis);
		int i = -1;

		
		while ((i = isr.read()) != -1) {
			System.out.print((char) i);
		}

		isr.close();
		fis.close();
	}

同樣的,字符流讀取文件放到字符數組作爲緩衝區去讀,速度更快。char[] buf = new char[1024];

void readFilebyArray() throws IOException {
		File file = new File("f://d.txt");
		if (!file.exists()) {
			return;
		}

		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis);// 字符流

		char[] buf = new char[1024];
		int len = -1;

		// 準備拷貝
		long begin = System.currentTimeMillis();
		while ((len = isr.read(buf)) != -1) {
			System.out.print(new String(buf, 0, len));
		}
		// 拷貝結束
		long end = System.currentTimeMillis();
		System.out.println("花費時間:");
		System.out.println(end - begin);
		// 先關高級流
		isr.close();

		fis.close();

	}
  •  附:標準輸入輸出:System.in  讀入
  •                                               out  輸出
  •                                                err  輸出錯誤信息(表現爲紅色字體)

RandomAccessFile  既不屬於輸入也不屬於輸出,就是一個普通類,支持對文件讀寫操作

seek(.lenth)追加

上一篇文章jiang 到兩種複製文件的方式:字節流和用緩衝流,現在介紹一種更快的方式:文件通道(屬於NIO)


	void copyfilebyFileChannel(File src, File target) throws IOException {
		FileInputStream fis = new FileInputStream(src);
		FileOutputStream fos = new FileOutputStream(target);
		FileChannel in = fis.getChannel();// 獲取文件通道
		FileChannel out = fos.getChannel();

		// 準備拷貝
		long begin = System.currentTimeMillis();

		in.transferTo(0, in.size(), out);// 將通道關聯並傳輸文件

		// 拷貝結束
		long end = System.currentTimeMillis();
		System.out.println("花費時間:");
		System.out.println(end - begin);
		
		out.close();
		in.close();
		fos.close();
		fis.close();
	}

 

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