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

本文介绍了一个使用Java NIO和CRC32算法来计算文件校验和的方法。通过将文件映射到内存,提高了文件校验的速度。示例代码展示了如何创建文件输入流、获取文件通道、创建CRC32实例、映射文件到内存缓冲区,并逐字节更新CRC32校验和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值