I/O基本操作

1. I/O流的概念

  Java对文本输入、输出的操作基础是流(I/O stream), 处理方式又可分为字节流(byte stream)处理、字符流(character stream)处理两种。整个"流"的方法如下图所示

Java stream
  • 缓存流
    缓存流就好比搬移很大一堆东西,一次性搬不完,那么就一小撮一小撮地去搬。输入或输出流先送到缓存流中,然后再从缓存中进行读写操作,缓存用完之后再去磁盘中搬运。缓存流的使用可以有效地减少I/O操作。

2. 代码测试

/**
 * Java文件文本操作测试
 */

public class test {
    public static void main(String[] args) {
        String path = "./src/1.txt";
        String outPath = "./src/out.txt";

        try ( // 读入文本并放到缓存流中
                FileReader fr = new FileReader(path);
                BufferedReader br = new BufferedReader(fr);
                // 以缓存流的方式写出
                FileWriter fw = new FileWriter(outPath);
                PrintWriter pw = new PrintWriter(fw)) {

            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                pw.println(line);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}
posted @ 2020-06-22 20:54  Maverickos  阅读(191)  评论(0编辑  收藏  举报