前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Java】BufferedReader与NIO读取文件性能测试

【Java】BufferedReader与NIO读取文件性能测试

作者头像
linapex
发布2019-03-26 10:11:08
2.4K0
发布2019-03-26 10:11:08
举报
文章被收录于专栏:区块链实战区块链实战

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

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

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

测试结果:

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

代码语言:javascript
复制
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 	<br><br>
 * 
 * 类名称:TNIO 		<br><br>
 * 
 * 创建人:LinApex@163.com 	<br><br>
 * 
 * 创建时间:2014-1-24 下午12:13:41 	<br><br>
 * 
 * 版本:1.0					<br><br>
 * 
 * 功能描述:
 */
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

(adsbygoogle = window.adsbygoogle || []).push({});

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014/01/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档