您的位置:首页 > 编程语言 > Java开发

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

2010-05-08 12:36 711 查看
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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: