java读取大数据量文本

luozhangwen 2010-08-04 10:01:29

package com.lzw;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadBigFile
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
readFile("test.txt");
long end = System.currentTimeMillis();
System.out.println(end - start);
}


/**
* 比用BufferedReader块4倍左右
*/
public static void readFile(String filePath)
{
int buffSize = 1024;
byte[] bytes = new byte[buffSize];
ByteBuffer byteBuffer = ByteBuffer.allocate(buffSize);

FileChannel channel = null;
try
{
channel = new RandomAccessFile(filePath, "r").getChannel(); //"r" = O_RDONLY
// StringBuffer sb = new StringBuffer(500);
while (channel.read(byteBuffer) != -1)
{
int size = byteBuffer.position();
byteBuffer.rewind();
byteBuffer.get(bytes);

String tmp = new String(bytes, 0, size);
// System.out.print(tmp);
//sb.append(tmp); //使用这个不需要\n,使用StrinbBuffer数据量超大的时候也会内存溢出
byteBuffer.clear();
}
channel.close(); //pls close in finally
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

}


...全文
132 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
yinxiaoqi 2010-08-04
  • 打赏
  • 举报
回复
[Quote=引用楼主 luozhangwen 的回复:]
Java code

package com.lzw;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel……
[/Quote]

这个 可以读取文档内容吗?

23,404

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧