1 package day9.lesson2;
2
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.OutputStreamWriter;
6
7 /*
8 2.5 字符流写数据的5种方式
9
10 void write(int c) 写一个字符
11 void write(char[] cbuf) 写入一个字符数组
12 void write(char[] cbuf, int off, int len) 写入字符数组的一部分
13 void write(String str) 写一个字符串
14 void write(String str, int off, int len) 写一个字符串的一部分
15
16 flush() 刷新流,之后还可以继续写数据
17 close() 关闭流,释放资源,但是在关闭之前会先刷新流。一旦关闭,就不能再写数据
18
19 */
20 public class OutputStreamWriterDemo {
21 public static void main(String[] args) throws IOException {
22 OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("stage2\\src\\day9\\lesson2\\osw2.txt"));
23
24 /*//写一个字符
25 osw.write(97);
26 osw.flush(); //写数据时得刷新,不然内容没有真正被写入文件,文件无内容
27
28 osw.write(98);
29 osw.flush();
30
31 osw.write(99);
32 osw.close(); //关闭之前会先刷新流
33
34 // osw.write(100); //IOException: Stream closed*/
35
36 //写一个字符数组
37 char[] chars = {'a', 'b', 'c', 'd'};
38 // osw.write(chars);
39 // osw.close();
40
41 //写入字符数组的一部分
42 // osw.write(chars, 0, chars.length);
43 // osw.flush();
44 // osw.write(chars, 1, 2);
45 // osw.close();
46
47 //写一个字符串
48 // osw.write("abcdefgh");
49 // osw.close();
50
51 //写字符串的一部分
52 osw.write("abcdefgh", 0, "abcdefgh".length());
53 osw.flush();
54 osw.write("abcdefgh", 1, 3);
55 osw.close();
56 }
57 }
1 package day9.lesson2;
2
3 import java.io.FileInputStream;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6
7 /*
8 2.6 字符流读数据的两种方式
9 int read() 一次读一个字符数据
10 int read(char[] cbuf) 一次读一个字符数组数据
11 */
12 public class InputStreamReaderDemo {
13 public static void main(String[] args) throws IOException {
14 InputStreamReader isr = new InputStreamReader(new FileInputStream("stage2\\src\\day9\\lesson2\\osw2.txt"));
15 // InputStreamReader isr = new InputStreamReader(new FileInputStream("stage2\\src\\day9\\lesson2\\StringDemo.java"));
16
17 //一次读一个字符数据
18 /*int ch;
19 while ((ch=isr.read()) != -1){
20 System.out.print((char)ch);
21 } //abcdefghbcd*/
22
23 //一次读一个字符数组数据
24 char[] chars = new char[1024];
25 int len;
26 while ((len=isr.read(chars)) != -1){
27 System.out.print(new String(chars, 0, len));
28 } //abcdefghbcd
29
30 isr.close();
31 }
32 }