File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed
codes/basics/src/main/java/io/github/dunwu/javase/io Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .io ;
2+
3+ import java .io .File ;
4+ import java .io .FileReader ;
5+ import java .io .IOException ;
6+ import java .io .Reader ;
7+
8+ /**
9+ * @author Zhang Peng
10+ * @date 2018/4/26
11+ */
12+ public class FileReaderDemo {
13+
14+ // 将所有内容直接读取到数组中
15+ public static int read1 (Reader input , char [] c ) throws IOException {
16+ int len = input .read (c ); // 读取内容
17+ return len ;
18+ }
19+
20+ // 每次读取一个字符,直到遇到字符值为-1,表示读文件结束
21+ public static int read2 (Reader input , char [] c ) throws IOException {
22+ int temp = 0 ; // 接收每一个内容
23+ int len = 0 ; // 读取内容
24+ while ((temp = input .read ()) != -1 ) {
25+ // 如果不是-1就表示还有内容,可以继续读取
26+ c [len ] = (char ) temp ;
27+ len ++;
28+ }
29+ return len ;
30+ }
31+
32+ public static void main (String args []) throws Exception {
33+ // 第1步、使用File类找到一个文件
34+ File f = new File ("d:" + File .separator + "test.txt" );
35+
36+ // 第2步、通过子类实例化父类对象
37+ Reader input = new FileReader (f );
38+
39+ // 第3步、进行读操作
40+ char c [] = new char [1024 ];
41+ // int len = read1(input, c);
42+ int len = read2 (input , c );
43+
44+ // 第4步、关闭输出流
45+ input .close ();
46+ System .out .println ("内容为:" + new String (c , 0 , len )); // 把字符数组变为字符串输出
47+ }
48+ }
Original file line number Diff line number Diff line change 1+ package io .github .dunwu .javase .io ;
2+
3+ import java .io .File ;
4+ import java .io .FileWriter ;
5+ import java .io .Writer ;
6+
7+ /**
8+ * @author Zhang Peng
9+ * @date 2018/4/26
10+ */
11+ public class FileWriterDemo {
12+
13+ public static void main (String args []) throws Exception { // 异常抛出,不处理
14+ // 第1步、使用File类找到一个文件
15+ File f = new File ("d:" + File .separator + "test.txt" ); // 声明File对象
16+
17+ // 第2步、通过子类实例化父类对象
18+ Writer out = new FileWriter (f );
19+ // Writer out = new FileWriter(f, true); // 追加内容方式
20+
21+ // 第3步、进行写操作
22+ String str = "Hello World!!!\r \n " ;
23+ out .write (str ); // 将内容输出
24+
25+ // 第4步、关闭输出流
26+ out .close ();
27+ }
28+ }
You can’t perform that action at this time.
0 commit comments