首页 > 编程 > Java > 正文

java---IO流缓冲输入输出流

2019-11-06 07:46:19
字体:
来源:转载
供稿:网友

这里写图片描述

☆示例测试技术总结:方案1是最优的 1)有buffer比没有更快; 2)buffer放在中间层包装比放在外层更快; 3)按行或按块操作 比 按字节或字符操作更快(用Object流操作的速度 比 字节字符方式 更快) 4)缓冲区要结合流才可以使用,在流的基础上对流的功能进行了增强。


package cn.hncu.io.buffered;import java.io.BufferedInputStream;import java.io.DataInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;public class BufferedXXXStream { public static void main(String[] args) { // 只要演示使用buffered缓冲流和不使用缓冲流(而且缓冲流所在的位置)读取文件的速度进行比较 // bufferedRead1();//24 25 26左右的样子 // bufferedRead2();//80~90毫秒之间的样子 bufferedRead3();//27以上的样子 } PRivate static void bufferedRead3() { // 测试程序运行的时长 long time1 = System.currentTimeMillis(); File file = new File("files/buffered.txt"); if (!file.exists()) { System.out.println("文件没有找到...."); return; } byte[] buf = new byte[50]; // 方式3:buffered缓冲流放在最外层进行包装 try { BufferedInputStream bis = new BufferedInputStream( new DataInputStream(new FileInputStream(file))); int len = 0; while ((len = bis.read(buf)) != -1) { System.out.println(new String(buf, 0, len)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long time2 = System.currentTimeMillis(); System.out.println("程序运行的时长为(毫秒):" + (time2 - time1)); } private static void bufferedRead2() { // 测试程序运行的时长 long time1 = System.currentTimeMillis(); File file = new File("files/buffered.txt"); if (!file.exists()) { System.out.println("文件没有找到...."); return; } // 方式2:不使用buffered缓冲流 try { DataInputStream dis = new DataInputStream(new FileInputStream(file)); String line = ""; while ((line = dis.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long time2 = System.currentTimeMillis(); System.out.println("程序运行的时长为(毫秒):" + (time2 - time1)); } private static void bufferedRead1() { // 测试程序运行的时长 long time1 = System.currentTimeMillis(); File file = new File("files/buffered.txt"); if (!file.exists()) { System.out.println("文件没有找到...."); return; } // 方式1:将buffered缓冲流放在中间位置 try { DataInputStream dis = new DataInputStream(new BufferedInputStream( new FileInputStream(file))); String line = ""; while ((line = dis.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } long time2 = System.currentTimeMillis(); System.out.println("程序运行的时长为(毫秒):" + (time2 - time1)); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表