字符流读取写入文件

简介: 字符流读取写入文件

Reader: FileReader BufferedReader

Writer: FileWriter BufferedWriter

字符流读取写入文件都有这两种

单独用FileWriter写入文件会每次写入数据,磁盘都有一次写入导致效率低,使用BufferReader搭配使用会把缓冲区装满再进行写入,提高了写入的效率。

try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("aa1.txt", true));
            for (int i = 0; i < 10; i++) {
                bw.append("holle world!中文效果\n");
            }
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("字符流:");
        var m1 = System.currentTimeMillis();
        try {
            BufferedReader br = new BufferedReader(new FileReader("aa1.txt"));
            while (br.ready()) {
                System.out.println(br.readLine());
            }
            System.out.printf("字符流时间:%d毫秒%n", System.currentTimeMillis() - m1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

image.gif

java.io.InputStream 输入流,主要是用来读取文件内容的。

java.io.OutputStream 输出流,主要是用来将内容字节写入文件的

System.out.println("字节流:");
        try {
            var m2 = System.currentTimeMillis();
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("aa1.txt"));
            byte[] s = new byte[1024];
            int aa = 0;
            while ((aa = bis.read(s)) > 0) {
                System.out.println(new String(s, 0, aa));
            }
            bis.close();
            System.out.printf("字节流时间:%d毫秒%n", System.currentTimeMillis() - m2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

image.gif

byte[] s就是建立缓冲区读取字节

目录
相关文章
|
1月前
|
Linux Windows
写入文件
写入文件。
14 2
|
3月前
|
移动开发 Java Linux
IO流:字节输出流FileOutputStream的超详细用法
IO流:字节输出流FileOutputStream的超详细用法
|
4月前
|
C语言
从文件中读取一行
C 语言实例 - 从文件中读取一行。
34 3
|
4月前
|
XML C# 数据格式
C#读取写入文件的三种方式
最近对文件的操作比较频繁。这里记录一下常用的几种文件读写的方式。 我这里使用窗体来做测试,例子在文末,可下载。
52 0
|
5月前
|
存储 安全 编译器
C#中使用I/O文件流
流,即是二进制数值,文件和流 I/O(输入/输出)是指在存储媒介中传入或传出数据。在 .NET 中,System.IO命名空间包含允许以异步方式和同步方式对数据流和文件进行读取和写入操作的类型。这些命名空间还包含对文件执行压缩和解压缩的类型,以及通过管道和串行端口启用通信的类型。命名空间:System.IO程序集:System.Runtime.dll。
46 1
|
8月前
|
Shell 开发工具
读取文件
读取文件
28 3
|
8月前
字节、字符输入输出流
字节、字符输入输出流
33 0
|
C语言 Python
从一个字节流中进行按行读取
从一个字节流中进行按行读取
160 0
|
移动开发 C++ Windows
C++读取文件
C++读取文件
|
网络协议 测试技术 Go
带缓冲的 Reader 读文件 | 学习笔记
快速学习带缓冲的 Reader 读文件
99 0
带缓冲的 Reader 读文件 | 学习笔记