java例題學習:字符流例題

練習一:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/*
 * 需求:把當前項目目錄下的a.txt內容複製到當前項目目錄下的b.txt中
 * 
 * 數據源:
 * 		a.txt -- 讀取數據 -- 字符轉換流 -- InputStreamReader
 * 目的地:
 * 		b.txt -- 寫出數據 -- 字符轉換流 -- OutputStreamWriter
 */
public class CopyFileDemo {
	public static void main(String[] args) throws IOException {
		// 封裝數據源
		InputStreamReader isr = new InputStreamReader(new FileInputStream(
				"a.txt"));
		// 封裝目的地
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				"b.txt"));

		// 讀寫數據
		// 方式1
		// int ch = 0;
		// while ((ch = isr.read()) != -1) {
		// osw.write(ch);
		// }

		// 方式2
		char[] chs = new char[1024];
		int len = 0;
		while ((len = isr.read(chs)) != -1) {
			osw.write(chs, 0, len);
			// osw.flush();
		}

		// 釋放資源
		osw.close();
		isr.close();
	}
}


練習二:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
 * 由於我們常見的操作都是使用本地默認編碼,所以,不用指定編碼。
 * 而轉換流的名稱有點長,所以,Java就提供了其子類供我們使用。
 * OutputStreamWriter = FileOutputStream + 編碼表(GBK)
 * FileWriter = FileOutputStream + 編碼表(GBK)
 * 
 * InputStreamReader = FileInputStream + 編碼表(GBK)
 * FileReader = FileInputStream + 編碼表(GBK)
 * 
 /*
 * 需求:把當前項目目錄下的a.txt內容複製到當前項目目錄下的b.txt中
 * 
 * 數據源:
 * 		a.txt -- 讀取數據 -- 字符轉換流 -- InputStreamReader -- FileReader
 * 目的地:
 * 		b.txt -- 寫出數據 -- 字符轉換流 -- OutputStreamWriter -- FileWriter
 */
public class CopyFileDemo2 {
	public static void main(String[] args) throws IOException {
		// 封裝數據源
		FileReader fr = new FileReader("a.txt");
		// 封裝目的地
		FileWriter fw = new FileWriter("b.txt");

		// 一次一個字符
		// int ch = 0;
		// while ((ch = fr.read()) != -1) {
		// fw.write(ch);
		// }

		// 一次一個字符數組
		char[] chs = new char[1024];
		int len = 0;
		while ((len = fr.read(chs)) != -1) {
			fw.write(chs, 0, len);
			fw.flush();
		}

		// 釋放資源
		fw.close();
		fr.close();
	}
}

練習三

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
 * 需求:把c:\\a.txt內容複製到d:\\b.txt中
 * 
 * 數據源:
 * 		c:\\a.txt -- FileReader
 * 目的地:
 * 		d:\\b.txt -- FileWriter
 */
public class CopyFileDemo3 {
	public static void main(String[] args) throws IOException {
		// 封裝數據源
		FileReader fr = new FileReader("c:\\a.txt");
		// 封裝目的地
		FileWriter fw = new FileWriter("d:\\b.txt");

		// 讀寫數據
		// int ch = 0;
		int ch;
		while ((ch = fr.read()) != -1) {
			fw.write(ch);
		}
		
		//釋放資源
		fw.close();
		fr.close();
	}
}
註釋:代碼源於傳智播客

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