使用字符流(Writer、Reader)完成对文件的读写操作

字符流

  • 字符输出流:Writer,对文件的操作使用子类FileWriter
  • 字符输入流:Reader,对文件的操作使用子类FileReader
  • 每次操作的是一个字符
  • 文件字符操作流会自带缓存,默认大小为1024字节,在缓存满后,手动刷新或关闭时才会把数据写入文件。

如何选用字节流还是字符流

一般操作非文本文件时,使用字节流,操作文本文件时,建议使用字符流

使用字符流完成文件的读写操作

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 WriterAndReader {

    public static void main(String[] args) {
        out();
        in();
    }

    // 从文件读取数据
    private static void in() {
        File file = new File("F:/test.txt");
        try {
            Reader in = new FileReader(file);

            // 因为使用了处理过的字符流,所以缓冲数组cs的大小随意,都不会导致多读
            char[] cs = new char[3];
            int len = -1;
            StringBuilder sb = new StringBuilder();
            while ((len = in.read(cs)) != -1) {
                sb.append(new String(cs, 0, len));
            }
            in.close();
            System.out.println(sb);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 将数据写入到文件
    private static void out() {
        File file = new File("F:/test.txt");
        try {
            Writer out = new FileWriter(file, true);
            out.write("我爱Java");
            out.flush();
            out.close();
            System.out.println("数据写入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

猜你喜欢

转载自www.cnblogs.com/zxfei/p/10864155.html