IO之字符流

在程序中一個字符等於兩個字節。

1、字符輸出流:Writer

抽象類,需要通過FileWriter子類進行實例化

public FileWriter(File file) throws IOExcrption

【Writer類的常用方法】

* public  abstract void close(0 throws IOException 關閉輸出流

* public void write(String str) throws IOExcrption 將字符串輸出

* public void write(char[] cbuf) throws IOException 將字符數組輸出

* public abstaract void flush(0 throws IOEXception 強制清空緩存

實例:向文件中寫入數據

public class WriterDemo {
	public static void main(String[] args) {
		File f = new File("D:"+File.separator+"test.txt");
		try {
			FileWriter writer = new FileWriter(f);
			String str = "FileWriter";	
			//與OutputStream的區別就是不用將字符串變成數據,可以直接輸出字符串
			writer.write(str);
			writer.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

向文件中追加內容,和OutputStream一樣的方法:

public class WriterDemo {
	public static void main(String[] args) {
		File f = new File("D:"+File.separator+"test.txt");
		try {
			FileWriter writer = new FileWriter(f,true);
			String str = "\r\nFileWriter";	
			//與OutputStream的區別就是不用將字符串變成數據,可以直接輸出字符串
			writer.write(str);
			writer.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

2、字符輸入流:reader

抽象類,通過FileReader類進行實例化

【Reader類常用方法】

* public abstract void close() throws IOException 關閉輸出流

* public int  read() throws IOExcrption 讀取單個字符

public int read (char [] cbuf) throws IOExcrption  將內容讀取字符數組中,返回讀入的長度

public class ReaderDemo {
	public static void main(String[] args) {
		File file = new File("d:"+File.separator+"test.txt");
		try {
			FileReader reader = new FileReader(file);
			char c[] = new char[1024];
			int len = reader.read(c);
			reader.close();
			System.out.println("讀取內容:"+new String(c,0,len));		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

可以通過循環方式進行讀寫:

public class ReaderDemo {
	public static void main(String[] args) {
		File file = new File("d:"+File.separator+"test.txt");
		try {
			FileReader reader = new FileReader(file);
			char c[] = new char[1024];
			int temp = 0;
			int len =0;
			while ((temp = reader.read())!=-1) {
				c[len] = (char)temp;
				len++;
			}		

			reader.close();
			System.out.println("讀取內容:"+new String(c,0,len));		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}



發佈了20 篇原創文章 · 獲贊 3 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章