有一个大文件,假设为2GByte,类型为纯文本,换行分隔,每行数据固定为16Byte。
要从中删除前10万行数据,在 Java 中如何能够快速、低内存消耗的实现?

解决方案 »

  1.   

    RandomAccessFile将指针移动到10万行处,在将数据拷贝至另一个文件,删除原文件,新文件重命名顺便关注有什么更好的方法
      

  2.   

    给个刚做的源代码给你吧,自己去查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");
        }
    }