本文實例為大家分享了文件字符流的使用方法,供大家參考,具體內容如下
案例1:
讀取一個文件并寫入到另一個文件中,char[] 來中轉。
首先要在E盤下創建一個文本文檔,命名為test.txt,輸入一些字符串。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
public class Demo_5 { public static void main(String[] args) { FileReader fr= null ; //文件取出字符流對象(輸入流) FileWriter fw= null ; //寫入到文件(輸出流) try { fr= new FileReader( "e:\\test.txt" ); //創建一個fr對象 fw= new FileWriter( "d:\\test.txt" ); //創建輸出對象 char []c= new char [ 1024 ]; //讀入到內存 int n= 0 ; //記錄實際讀取到的字符數 while ((n=fr.read(c))!=- 1 ){ //String s=new String(c,0,n); fw.write(c, 0 ,n); } e.printStackTrace(); } finally { try { fr.close(); fw.close(); } catch (Exception e) { e.printStackTrace(); } } } } |
打開D盤的test.txt文件,出現相同的字符串。
案例2:為了提高效率引入了緩沖字符流
依然實現讀取一個文件并寫入到另一個文件中,直接操作String。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class Demo_6 { public static void main(String[] args) { BufferedReader br= null ; BufferedWriter bw= null ; try { FileReader fr= new FileReader( "e:\\test.txt" ); //先創建FileReader對象 br= new BufferedReader(fr); FileWriter fw= new FileWriter( "d:\\test1.txt" ); //創建FileWriter對象 bw= new BufferedWriter(fw); String s= "" ; while ((s=br.readLine())!= null ){ //循環讀取文件,s不為空即還未讀完畢 bw.write(s+ "\r\n" ); //輸出到磁盤,加上“\r\n”為了實現換行 } } catch (Exception e){ e.printStackTrace(); } finally { try { br.close(); bw.close(); } catch (Exception e) { e.printStackTrace(); } } } } |
打開D盤的test1.txt文件,出現相同的字符串。
總結:字節流操作對象byte,字符流操作對象char,緩沖字符流操作對象String。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/cxq1126/archive/2017/08/11/7345705.html