java 匿名 filereader_【Java】BufferedReader与NIO读取文件性能测试

说你CSV读入效率太差,是指你用的是行读方式,行读是效率比较慢的一种读法。

请问还有什么高效的读取大文件的方法吗?

我对 BufferedReader  与 NIO  读取文件效果做了一个简单的测试

测试结果:

根据测试 BufferedReader 与  NIO 读取效果是差不多的. 如果 缓存 配置不好,则NIO效果比BufferedReader慢。

package test.com.linapex.nio;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileReader;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

/**

* 项目名称:LinApex-Student 

*

* 类名称:TNIO 

*

* 创建人:LinApex@163.com 

*

* 创建时间:2014-1-24 下午12:13:41 

*

* 版本:1.0

*

* 功能描述:

*/

public class TNIO

{

public static void doBufferReadFile(File file) throws Exception

{

BufferedReader reader = null;

try

{

reader = new BufferedReader(new FileReader(file));

String str = null;

int num = 0;

while ((str = reader.readLine()) != null)

{

num++;

}

} finally

{

reader.close();

}

}

public static void doNioReadFile(File file) throws Exception

{

String enterStr = "\n";

FileChannel inChannel = new FileInputStream(file).getChannel();

ByteBuffer buffer = ByteBuffer.allocate(BSIZE);

StringBuilder newlinesBui = new StringBuilder();

while (inChannel.read(buffer) != -1)

{

buffer.flip();

//数据组合.

String content = new String(buffer.array());

newlinesBui.append(content).toString();

int fromIndex = 0;

int endIndex = -1;

//循环找到 \n

while ((endIndex = newlinesBui.indexOf(enterStr, fromIndex)) > -1)

{

//得到一行

String line = newlinesBui.substring(fromIndex, endIndex);

//System.out.print(line);

fromIndex = endIndex + 1;

}

newlinesBui.delete(0, fromIndex);

buffer.clear();

}

}

final static int BSIZE = 1024 * 1024;

public static void main(String[] args) throws Exception

{

long begin = System.currentTimeMillis();

File csvFile = new File("D:\\baiduyundownload\\test\\2000W\\1-200W.csv");

doNioReadFile(csvFile);

//bufferRead(csvFile);

long end = System.currentTimeMillis();

System.out.println(end - begin);

}

}

NIO(缓冲1M)测试三次结果如下:

2418

2390

2370

BufferReader测试三次结果如下:

2547

2524

2535

NIO(缓冲1024字节,将 BSIZE 改成 1024 )测试三次结果如下:

3366

3318

3372

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值