Java IO流---字符流

 

Writer:写入字符流的抽象类,子类必须实现的方法有 write(char [],int,int)  flush()  close(),

    对文件的操作,一般由其子类FileWriter完成。

Reader:读取字符流的抽象类,子类必须实现的方法有 read(char [].int,int)  close(),

    对文件的操作,一般由其子类FileReader完成。

字符流每次操作的最小单位是一个字符,文件字符操作流自带缓存,在缓存满了之后或者手动刷新或者关闭流,数据才会写入文件。

字符流的底层实现是基于字节流。

实际操作中如何选择 字节流字符流???

  一般操作非文本文件(图片、视频)使用字节流,操作文本文件使用字符流。

代码示例:

 

package com.seven.javaSE;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class CharStream {
    public static void main(String[] args) {
        out();
        in();
    }
    
    //字符输出流
    public static void out() {
        
        File file = new File("C:/TestFile/hello.txt");
        try {
            Writer out = new FileWriter(file,true);
            String str = "一步一步,步步为营。";
            //字符流可以直接将字符串写入文件,不用将字符串转换成字节数组
            out.write(str);
            out.close();
            System.out.println("字符写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //字符输入流
    public static void in() {
        File file = new File("C:/TestFile/hello.txt");
        try {
            Reader read= new FileReader(file);
            StringBuffer sb = new StringBuffer();
            //字符数组即使长度为1,也可以完成文件读取任务
            char [] cc = new char[1];
            int len=-1;
            while((len=read.read(cc))!=-1) {
                sb.append(cc, 0, len);
            }
            read.close();
            System.out.println(sb);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

 

 

 

 

    

posted @ 2022-06-16 21:21  藤原豆腐渣渣  阅读(22)  评论(0编辑  收藏  举报