java 写文件效率_java大文件读取效率对比

分别采用三种方式读取大小为74GB共约6亿条记录的文件,BufferedReader 性能最好,RandomAccessFile最差,性能差距超过1百倍

 
 

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 {

}

}

BufferedReader 执行时间:244007当前输出第:600037902条数据

Scanner 执行时间:2219763当前输出第:600037902条数据

RandomAccessFile 执行时间:35246077当前输出第:600037902条数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值