您的位置:首页 > Web前端

IO加强之缓冲输入输出流测试

2017-04-01 18:19 323 查看
import java.io.BufferedInputStream;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.IOException;

import org.junit.Test;

//缓冲输入输出流的测试,通过以下三种情况来判断有没有buffer和buffer的位置对读取文件的影响

//1.不加缓存buffer

//2.将缓存buffer加在内部

//3.将缓存buffer加在外部

public class BuffereDemo {
@Test
public void demo1() throws IOException{
//不加缓冲输入输出流  读取结果14秒
long t1 = System.currentTimeMillis();//获取当前系统时间
DataInputStream din = new DataInputStream(
                    new FileInputStream("test.txt")
                    );
String str = null;
while((str = din.readLine())!=null){
System.out.println(str);
}
long t2 = System.currentTimeMillis();//获取当前系统时间
System.out.println("法1运行时间:"+(t2-t1));
}

@Test
//内部加缓存   读取结果 3秒
public void demo2() throws IOException{
long t1 = System.currentTimeMillis();
DataInputStream din = new DataInputStream(
new BufferedInputStream(
new FileInputStream("test.txt")
)
);
String str = null;
while((str = din.readLine())!=null){
System.out.println(str);
}
long t2 = System.currentTimeMillis();
System.out.println("法2运行时间:"+(t2-t1));
}

@Test

//   外部缓存   读取结果9秒
public void demo3() throws IOException{
long t1 = System.currentTimeMillis();
BufferedInputStream bin = new BufferedInputStream(
                    new DataInputStream(
                                new FileInputStream("test.txt")    
                            )
                 );
byte buf[] = new byte[30];
int len=0;
while( (len=bin.read(buf))!=-1 ){
System.out.println( new String(buf,0,len));
}
long t2 = System.currentTimeMillis();
System.out.println("法3运行时间:"+(t2-t1));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 缓存 buffer