利用java内存映射文件机制实现CRC循环冗余校验

import java.nio.MappedByteBuffer;   
import java.nio.channels.FileChannel;   
import java.util.zip.CRC32;   
public static void main(String[] args){   
            try {                               //对

import java.nio.MappedByteBuffer;  
import java.nio.channels.FileChannel;  
import java.util.zip.CRC32;  
public static void main(String[] args){  
            try {                               //对文件进行crc校验  
            long begin = System.currentTimeMillis();  
            FileInputStream in = new FileInputStream("code.py");//指定目标文件  
            FileChannel channel = in.getChannel(); //从文件中获取一个通道  
            CRC32 crc = new CRC32();  
            int length = (int)channel.size();  
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length); //用只读模式从该通道获取字节缓冲,实现文件到内存的映射  
            for(int i = 0;i<length;i++)  
            {  
                int c = buffer.get(i);  
                crc.update(c);//按字节做crc  
            }  
            System.out.println("crc校验和:"+(Long.toHexString(crc.getValue())).toUpperCase());  
            long end = System.currentTimeMillis();  
            System.out.println("运行"+(end-begin)+"ms");  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.zip.CRC32;
public static void main(String[] args){
   try {              //对文件进行crc校验
   long begin = System.currentTimeMillis();
   FileInputStream in = new FileInputStream("code.py");//指定目标文件
   FileChannel channel = in.getChannel(); //从文件中获取一个通道
   CRC32 crc = new CRC32();
   int length = (int)channel.size();
   MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length); //用只读模式从该通道获取字节缓冲,实现文件到内存的映射
   for(int i = 0;i<length;i++)
   {
    int c = buffer.get(i);
    crc.update(c);//按字节做crc
   }
   System.out.println("crc校验和:"+(Long.toHexString(crc.getValue())).toUpperCase());
   long end = System.currentTimeMillis();
   System.out.println("运行"+(end-begin)+"ms");
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}

运行结果:

crc校验和:4831ACAC

运行16ms

你可能感兴趣的:(java,c,exception,String,buffer,import)