讀寫文件

package IO;
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class FileReaderDemo {
 
	public static void main(String[] args) {
		// 讀取文件的方式一:逐個字符來讀取文本文件
		FileReader fr = null;
		try {
			fr = new FileReader("Demo.txt");
 
			int ch = fr.read();
			while (ch != -1) {
				System.out.print((char) ch);
				ch = fr.read();
			}
			System.out.println();
		} catch (IOException e) {
			System.out.println("異常:" + e.toString());
		} finally {
			try {
				if (fr != null)
					fr.close();
			} catch (IOException e) {
				System.out.println("異常:" + e.toString());
			}
		}
		
		//讀取文件方式二:使用數組來讀取文本文件
		FileReader fr1 = null;
		try {
			fr1 = new FileReader("Demo.txt");
			char [] buf = new char[1024];
			int num = 0;
			while((num = fr1.read(buf))!=-1) {
				System.out.println(new String(buf,0,num));
			}
		}catch(IOException e) {
			System.out.println("異常:" + e.toString());
		}finally {
			try {
			if(fr1!=null)
			fr1.close();
			}catch(IOException e) {
				System.out.println("異常:" + e.toString());
			}
		}
		
		//方法三:用緩衝區讀取文本文件
		//通過查源碼得知方法三內部實現時是使用數組形式來緩衝字符數據的
		FileReader fr2 = null;
		BufferedReader bufr = null;
		try {
			fr2 = new FileReader("Demo.txt");
			bufr = new BufferedReader(fr2);
			String line = null;
			//BufferedReader提供了按行讀取文本文件的方法readLine()
			//readLine()返回行有效數據,不包含換行符,未讀取到數據返回null
			while((line = bufr.readLine())!=null) {
				System.out.println(line);	
			}
		}catch(IOException e) {
			System.out.println("異常:" + e.toString());
		}finally {
			try {
			if(bufr!=null)
			bufr.close();
			}catch(IOException e) {
				System.out.println("異常:" + e.toString());
			}
		}
	}
 
}

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