FileReader和FileWriter源碼分析
1. FileReader 源碼(基于jdk1.7.40)
1
2
3
4
5
6
7
8
9
10
11
12
|
package java.io; public class FileReader extends InputStreamReader { public FileReader(String fileName) throws FileNotFoundException { super ( new FileInputStream(fil java io系列 21 之 InputStreamReader和OutputStreamWritereName)); } public FileReader(File file) throws FileNotFoundException { super ( new FileInputStream(file)); } public FileReader(FileDescriptor fd) { super ( new FileInputStream(fd)); } } |
從中,我們可以看出FileReader是基于InputStreamReader實現的。
2. FileWriter 源碼(基于jdk1.7.40)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
package java.io; public class FileWriter extends OutputStreamWriter { public FileWriter(String fileName) throws IOException { super ( new FileOutputStream(fileName)); } public FileWriter(String fileName, boolean append) throws IOException { super ( new FileOutputStream(fileName, append)); } public FileWriter(File file) throws IOException { super ( new FileOutputStream(file)); } public FileWriter(File file, boolean append) throws IOException { super ( new FileOutputStream(file, append)); } public FileWriter(FileDescriptor fd) { super ( new FileOutputStream(fd)); } } |
從中,我們可以看出FileWriter是基于OutputStreamWriter實現的。
示例程序
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter;; import java.io.FileReader; import java.io.IOException; /** * FileReader 和 FileWriter 測試程序 * * */ public class FileReaderWriterTest { private static final String FileName = "file.txt" ; private static final String CharsetName = "utf-8" ; public static void main(String[] args) { testWrite(); testRead(); } /** * OutputStreamWriter 演示函數 * */ private static void testWrite() { try { // 創建文件“file.txt”對應File對象 File file = new File(FileName); // 創建FileOutputStream對應FileWriter:將字節流轉換為字符流,即寫入out的數據會自動由字節轉換為字符。 FileWriter out = new FileWriter(file); // 寫入10個漢字 out1.write( "字節流轉為字符流示例" ); // 向“文件中”寫入"0123456789"+換行符 out1.write( "0123456789\n" ); out1.close(); } catch (IOException e) { e.printStackTrace(); } } /** * InputStreamReader 演示程序 */ private static void testRead() { try { // 方法1:新建FileInputStream對象 // 新建文件“file.txt”對應File對象 File file = new File(FileName); FileReader in1 = new FileReader(file); // 測試read(),從中讀取一個字符 char c1 = ( char )in1.read(); System.out.println( "c1=" +c1); // 測試skip(long byteCount),跳過4個字符 in1.skip( 6 ); // 測試read(char[] cbuf, int off, int len) char [] buf = new char [ 10 ]; in1.read(buf, 0 , buf.length); System.out.println( "buf=" +( new String(buf))); in.close(); } catch (IOException e) { e.printStackTrace(); } } } |
運行結果:
c1=字
buf=流示例0123456
以上所述是小編給大家介紹的Java 中的FileReader和FileWriter源碼分析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!