nio 大文件映射

用MappedByteBuffer  的方法来读取大文件,实测速度远远快于普通IO读写速度

 

@SuppressWarnings("resource")
public static void readFile3() {
MappedByteBuffer buffer=null;
try {
buffer=new RandomAccessFile("D:\\catalina.out","rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1253244);
int sum=0;
int n;
int line = 0;
System.out.println("开始时间:" + new Date());
long t1=System.currentTimeMillis();
for(int i=0;i<1253244;i++){
n=0x000000ff&buffer.get(i);
byte b = buffer.get(i);
sum+=n;
if(b==10){
line++;
}
//System.out.print( (char)b);
}
long t=System.currentTimeMillis()-t1;
System.out.println("结束时间:"+ sum + " "+ new Date());
System.out.println("sum:"+sum+" time:"+t +"line: " + line);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

posted on 2017-04-06 14:01  zhuanagyan  阅读(149)  评论(0编辑  收藏  举报

导航