python的io流详解_java IO流效率对比

我们使用IO进行文本读写,那么就会考虑到读写的效率。不同IO流的用法带来的运行速度是不一致的,除了我们之前分类学习的种类外,还有一种缓冲流,是专门用于效率增加方面的,在文本读写效率上进行提升。下面我们就缓冲流的概念进行讲解。同时带来不同IO流效率的对比。

1.缓冲流说明

缓冲流,也叫高效流,是对4个基本的FileXxx 流的增强,所以也是4个流,按照数据类型分类:字节缓冲流:BufferedInputStream,BufferedOutputStream

字符缓冲流:BufferedReader,BufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。

2.字符流和缓冲字符流的对比public class IOTest {

public static void main(String[] args) throws IOException {

// 数据准备

dataReady();

File data = new File("C:/Mu/data.txt");

File a = new File("C:/Mu/a.txt");

File b = new File("C:/Mu/b.txt");

File c = new File("C:/Mu/c.txt");

long start = System.currentTimeMillis();

copy(data, a);

long end = System.currentTimeMillis();

long start2 = System.currentTimeMillis();

copyChars(data, b);

long end2 = System.currentTimeMillis();

long start3 = System.currentTimeMillis();

bufferedCopy(data, c);

long end3 = System.currentTimeMillis();

System.out.println("普通字节流1耗时:" + (end - start) + " ms,文件大小:" + a.length() / 1024 + " kb");

System.out.println("普通字节流2耗时:" + (end2 - start2) + " ms,文件大小:" + b.length() / 1024 + " kb");

System.out.println("缓冲字节流耗时:" + (end3 - start3) + " ms,文件大小:" + c.length() / 1024 + " kb");

}

// 普通字符流不使用数组

public static void copy(File in, File out) throws IOException {

Reader reader = new FileReader(in);

Writer writer = new FileWriter(out);

int ch = 0;

while ((ch = reader.read()) != -1) {

writer.write((char) ch);

}

reader.close();

writer.close();

}

// 普通字符流使用字符流

public static void copyChars(File in, File out) throws IOException {

Reader reader = new FileReader(in);

Writer writer = new FileWriter(out);

char[] chs = new char[1024];

while ((reader.read(chs)) != -1) {

writer.write(chs);

}

reader.close();

writer.close();

}

// 缓冲字符流

public static void bufferedCopy(File in, File out) throws IOException {

BufferedReader br = new BufferedReader(new FileReader(in));

BufferedWriter bw = new BufferedWriter(new FileWriter(out));

String line = null;

while ((line = br.readLine()) != null) {

bw.write(line);

bw.newLine();

bw.flush();

}

// 释放资源

bw.close();

br.close();

}

// 数据准备

public static void dataReady() throws IOException {

StringBuilder sb = new StringBuilder();

for (int i = 0; i 

sb.append("abcdefghijklmnopqrstuvwxyz");

}

OutputStream os = new FileOutputStream(new File("C:/Mu/data.txt"));

os.write(sb.toString().getBytes());

os.close();

System.out.println("完毕");

}

}

运行结果:普通字符流1耗时:1337 ms,文件大小:15234 kb

普通字符流2耗时:82 ms,文件大小:15235 kb

缓冲字符流耗时:205 ms,文件大小:15234 kb

以上是java IO流效率的对比实例,缓冲字符流相对而言的优势并不是那么大,这是因为在使用上我们以缓冲流的方法用的居多,想要学习的可以在课外找寻资料。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值