java大文件读取效率对比

分别采用三种方式读取大小为74GB共约6亿条记录的文件,BufferedReader 性能最好,RandomAccessFile最差,性能差距超过1百倍
<pre>
public static void scannerReader(String filename){
File f = new File(filename);
if(f.exists() && f.isFile() && f.length()>0){
try {
long times=0;
long startTime = System.currentTimeMillis();
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String temp = sc.nextLine();
times++;
}
sc.close();
long endTime = System.currentTimeMillis();
System.out.println("Scanner 执行时间:"+(endTime-startTime) +"当前输出第:"+times+"条数据");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void bufferReader(String filename) throws Exception{
BufferedReader reader = null;
try {
File read= FileUtils.getFile(filename);
reader = new BufferedReader(new FileReader(read.getAbsoluteFile()));
String line = null;
long times=0;
long startTime = System.currentTimeMillis();
while((line = reader.readLine()) != null) {
times++;
}
long endTime = System.currentTimeMillis();
System.out.println("BufferedReader 执行时间:"+(endTime-startTime) +"当前输出第:"+times+"条数据");
} catch (IOException e) {
e.printStackTrace();
}finally {
}
}
public static void ranrReader(String filename)throws Exception{
RandomAccessFile raf = null;
FileChannel fc = null;
try {
raf = new RandomAccessFile(filename, "r");
//raf.seek(0);
fc = raf.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(100000);
int readcount = -1;
long times=0;
long startTime = System.currentTimeMillis();
while ((readcount = fc.read(buffer)) != -1) {
String line = raf.readLine();
times++;
}
long endTime = System.currentTimeMillis();
System.out.println("RandomAccessFile 执行时间:"+(endTime-startTime) +"当前输出第:"+times+"条数据");
} catch (Exception e) {
e.printStackTrace();
}finally {
}
}
</pre>
BufferedReader 执行时间:244007当前输出第:600037902条数据
Scanner 执行时间:2219763当前输出第:600037902条数据
RandomAccessFile 执行时间:35246077当前输出第:600037902条数据

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 前不久准备写一个关于文本处理的小程序,需要高效地对文本进行读取。于是就归纳了一下常见的文件读取方法,并测试了...
    djjowfy阅读 5,362评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,086评论 18 399
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,473评论 11 349
  • 申明一下这个内容是在weex项目中的,地址在这里 Scripts There are several script...
    EmptyWalker阅读 7,923评论 1 1
  • 一、实战配置: 电脑:联想v480,系统win10,64bit,采用UEFI、GPT分区(如何查看?——打开运行,...
    gg5d阅读 56,911评论 3 18