Java 中从大文件中删除部分数据的问题

holy_phoenix 2005-11-18 06:28:55
有一个大文件,假设为2GByte,类型为纯文本,换行分隔,每行数据固定为16Byte。
要从中删除前10万行数据,在 Java 中如何能够快速、低内存消耗的实现?
...全文
315 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
holy_phoenix 2005-11-22
  • 打赏
  • 举报
回复
谢谢楼上诸位!
kingofhawks 2005-11-21
  • 打赏
  • 举报
回复
关注.
lanseqingxu 2005-11-18
  • 打赏
  • 举报
回复
给个刚做的源代码给你吧,自己去查nio包中相关类的说明:
----------------------
import java.io.*;
import java.nio.*;
import java.util.zip.*;
import java.nio.channels.*;

/**
* 比较传统文件输入和内存映射两种方法对文件进行CRC校验的效率
* @author muz
*
*/

public class CompareCRC {

public static void main(String[] args) {
try{
if(args.length == 0){
File path = new File(".");
args = new String[] {path.getCanonicalFile() + "filename"};//filename为你要校验的文件
}

FileInputStream in = new FileInputStream(args[0]);
System.out.println("start verify...");
CRC.verify(in);
NIOCRC.verify(in);
in.close();
}
catch(IOException e){
e.printStackTrace();
}
}

}

/**
* 使用传统文件输入的CRC校验
* @author muz
*
*/
class CRC{

public static void verify(FileInputStream in) throws IOException{
CRC32 crc = new CRC32();
int c;
long start = System.currentTimeMillis();

while((c = in.read()) != -1)
crc.update(c);

long end = System.currentTimeMillis();
System.out.println(Long.toHexString(crc.getValue()));
System.out.println("CRC verification used " + (end - start) + " milliseconds");
}

}

/**
* 使用内存映射的CRC校验
* @author muz
*
*/
class NIOCRC{

public static void verify(FileInputStream in) throws IOException{
FileChannel channel = in.getChannel();

CRC32 crc = new CRC32();
long start = System.currentTimeMillis();

MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY,0,(int)channel.size());

while(buffer.hasRemaining())
crc.update(buffer.get());

long end = System.currentTimeMillis();

System.out.println(Long.toHexString(crc.getValue()));
System.out.println("NIOCRC verification used " + (end - start) + " milliseconds");
}
}
holy_phoenix 2005-11-18
  • 打赏
  • 举报
回复
楼上三位能不能详细说明一下?

谢谢
lanseqingxu 2005-11-18
  • 打赏
  • 举报
回复
对,内存映射会快10-20倍
believefym 2005-11-18
  • 打赏
  • 举报
回复
用nio可能更好一些
blddp 2005-11-18
  • 打赏
  • 举报
回复
RandomAccessFile将指针移动到10万行处,在将数据拷贝至另一个文件,删除原文件,新文件重命名

顺便关注有什么更好的方法

62,614

社区成员

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

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