2020.7.31第二十五天

1今天学习字符流

Reader与Writer 和其子类都是处理字符流的相关类。字符流可以对流数据以一个字符的长度为单位来处理,并进行适当的字符编码转换处理,一般字符流都用来操作纯文本文件。

(1)字符输出流。
Writer是字符输出流,该类是-一个抽象类,所以需要使用子类FileWriter 类来操作文件。

 1 import java.io. FileWriter;
 2 import java.io.IOException;
 3 public  class WriterDemo{
 4 public static void main(String[] args) throws IOException {
 5 write() ;
 6 }
 7 public static void write() throws IOException {
 8 FileWriter fw =new FileWriter ("D:/Hello1.txt");
 9 fw.write ("Hello C++!");
10 fw.close();
11 }
12 }

 直接追加

 1 import java.io. FileWriter;
 2 import java.io.IOException;
 3 public  class WriterDemo{
 4 public static void main(String[] args) throws IOException {
 5 write() ;
 6 }
 7 public static void write() throws IOException {
 8 FileWriter fw =new FileWriter ("D:/Hello1.txt",true);
 9 fw.write ("aaaa!");
10 fw.close();
11 }
12 }

(2)字符输入流。
Reader是一个字符输入流,但它是一个抽象类,所以必须由其子类FileReader来实例化。

 1 import java.io. FileReader;
 2 import java. io. IOException;
 3 import java. io. Reader;
 4 public class  ReaderDemo {
 5 public static void main(String[] args) throws IOException {
 6 reader();
 7 }
 8 public static void reader() throws IOException{
 9 Reader r=new FileReader ("D:/Hello1.txt") ;
10 char[] buf = new char[1024];
11 int len=0;
12 while((len=r.read (buf)) !=-1) {
13 String s =new String (buf,0,len) ;
14 System.out.println(s) ;
15 }
16 r.close();
17 }
18 }

(3).字节流与字符流的区别

字节流与字符流的区别主要体现在以下两点。

(1)读写单位不同:字节流以字节(8bit) 为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

(2)处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。

结论:只要是处理纯文本数据,就优先考虑使用字符流,此外,都使用字节流。

2.遇到的问题:没有弄清楚使用字节流和字符流的使用方法

3.明天继续学习第12章

原文地址:https://www.cnblogs.com/Nojava/p/13412080.html