字符流 :讀的也是二進制文件,他會幫我們解碼成我們看的懂的字符。
字符流 = 字節流 + 解碼
(一)字符輸入流:Reader : 它是字符輸入流的根類 ,是抽象類
FileReader :文件字符輸入流 ,讀取字符串。
用法:
1.找到目標文件
2.建立數據的通道
3.建立一個緩沖區
4.讀取數據
5.關閉資源。
(二)字符流輸出流: Writer : 字符輸出流的根類 ,抽象的類
FileWiter :文件數據的輸出字符流
使用注意點:
1.FileReader內部維護了一個1024個字符的數組,所以在寫入數據的時候,它是現將數據寫入到內部的字符數組中。
如果需要將數據寫入到硬盤中,需要用到flush()或者關閉或者字符數組數據存滿了。
2.如果我需要向文件中追加數據,需要使用new FileWriter(File , boolean)構造方法 ,第二參數true
3.如果指定的文件不存在,也會自己創建一個。
字符輸出流簡單案例
1 import java.io.File;
2 import java.io.FileWriter;
3 import java.io.IOException;
4
5 public class fileWriter {
6
7 /**
8 * @param args
9 * @throws IOException
10 */
11 public static void main(String[] args) throws IOException {
12 // TODO Auto-generated method stub
13 testFileWriter();
14
15 }
16
17 public static void testFileWriter() throws IOException{
18
19 //1.找目標文件
20 File file = new File("D:\\a.txt");
21 //2.建立通道
22 FileWriter fwt = new FileWriter(file,true); //在文件後面繼續追加數據
23 //3.寫入數據(直接寫入字符)
24 fwt.write("繼續講課");
25 //4.關閉數據
26 fwt.close();
27 }
28 }
字符輸入流簡單案例
1 import java.io.File;
2 import java.io.FileReader;
3 import java.io.IOException;
4
5 public class fileReader {
6
7 public static void main(String[] args) throws IOException {
8
9 //testFileReader();
10 testFileReader2();
11 }
12 //(1)輸入字符流的使用 這種方式效率太低。
13 public static void testFileReader() throws IOException{
14
15 //1.找目標文件
16 File file = new File("D:\\a.txt");
17
18 //2.建立通道
19 FileReader frd = new FileReader(file);
20
21 //3.讀取數據
22 int content = 0; //讀取單個字符。效率低
23 while ((content = frd.read()) != -1) {
24 System.out.print((char)content);
25 }
26
27 //4.關閉流
28 frd.close();
29 }
30
31 //(2)
32 public static void testFileReader2() throws IOException{
33
34 //1.找目標文件
35 File file = new File("D:\\a.txt");
36
37 //2.建立通道
38 FileReader frd = new FileReader(file);
39
40 //3.建立一個緩沖區 ,字符數組
41 char[] c = new char[1024];
42 int length = 0;
43
44 //4.讀取數據
45 while ((length = frd.read(c))!= -1) {
46 //字符串輸出
47 System.out.println(new String(c,0,length));
48 }
49 //5.關閉資源
50 frd.close();
51 }
52 }