java大文本读取(几个G的文本)

public class BigFileRead {
public static void main(String[] arg) {
try {
int bufSize=1024;
byte[] bs = new byte[bufSize];
ByteBuffer byteBuf = ByteBuffer.allocate(1024);
FileChannel channel = new RandomAccessFile("D:\\DOC_bao\\hyip_app_user_request_old.log","r").getChannel();

while(channel.read(byteBuf)!=-1){
int size = byteBuf.position();
byteBuf.rewind();
byteBuf.get(bs);
System.out.println(new String(bs,0,size,"GBK"));
byteBuf.clear();
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}

//读取行(升级版)
public static void main(String[] arg) {

try {
Date start = new Date();
int count = 0;
int countLoop = 0;
String tailStr = "";
int bufSize = 1024 * 1024 * 20;
// int bufSize = 16;
byte[] bs = new byte[bufSize];
ByteBuffer byteBuf = ByteBuffer.allocate(bufSize);
// FileChannel channel = new RandomAccessFile("D:\\DOC_bao\\hyip_app_user_request_old.log","r").getChannel();
FileChannel channel = new RandomAccessFile("D:\\var\\log\\hyip\\hyip_app_user_request.log", "r").getChannel();
// FileChannel channel = new RandomAccessFile("D:\\DOC_bao\\hyip_app_user_request.log.2013-06-20", "r").getChannel();
while (channel.read(byteBuf) != -1) {
countLoop++;
int size = byteBuf.position();
byteBuf.rewind();
byteBuf.get(bs);
String bufferStr = new String(bs, 0, size, "utf-8");

if (bufferStr.indexOf("\n") >= 0) {
String[] b = bufferStr.split("\\n");
int len = b.length;

if (len > 0) {
b[0] = tailStr + b[0];
//如果最后一个是换行符,说明是整行,直接处理,否则放在临时变量里下次处理。
if (bufferStr.lastIndexOf("\n") == bufferStr.length() - 1) {
tailStr = "";
len++;
} else {
tailStr = b[len - 1];
}
for (int i = 0; i < len - 1; i++) {
count++;
// System.out.print(count + ":" + b[i]);
DBOperate(b[i]);
}
}
} else { //如果一行数据过大,超过缓冲区,就追加到临时变量里。
tailStr += bufferStr;
}
byteBuf.clear();
}

if (tailStr != null && tailStr.length() > 0) {
count++;
// System.out.print(count + ":" + tailStr);
DBOperate(tailStr);
}

Date end = new Date();
System.out.println(start);
System.out.println(end);
Long spendTime =end.getTime() -start.getTime();
System.out.println("spend time:"+spendTime+"");
System.out.println(count);
// System.out.println(countLoop);
} catch (IOException e) {
e.printStackTrace();
}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值