MD5加密实现版本控制效果如何?

参考文章:http://www.iteye.com/topic/1127319

看一个文件是否有更新,可以使用md5来获取MD5码,以此来比对看是否有修改。对于小文件来说这个可以使用,效率不影响。但是,对于大文件来说,md5加密大文件,获取的时间是比较长的,效率也降低了不少。

 

参考文章还提到:使用Java读文件时,采用缓存技术可以加密大文件的时间大大减少,使用了FileChannel 类。

 

File: K:\Games\World of Warcraft\Data\common.MPQ
Size: 2226587191 bytes
Modified: 2008年11月19日 星期三, 12:57:24
MD5: CD9F9C5523F3BA3866B81CCC74ED6476


java运行结果,毫秒
耗时:12672,cd9f9c5523f3ba3866b81ccc74ed6476

NIO简单版例子:

                String hashType = "MD5";
		FileInputStream fStream = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance(hashType);
			fStream = new FileInputStream(
					//"K:\\Games\\World of Warcraft\\Scan.dll");
					//"K:\\Games\\World of Warcraft\\Data\\patch-3.MPQ");
					"K:\\Games\\World of Warcraft\\Data\\common.MPQ");
			FileChannel fChannel = fStream.getChannel();
			ByteBuffer buffer = ByteBuffer.allocate(8*1024);
			long s = System.currentTimeMillis();
			for ( int count = fChannel.read( buffer ); count !=-1 ; count = fChannel.read( buffer )
				) {
				buffer.flip();
				md5.update( buffer );
				if( !buffer.hasRemaining() ){
					//System.out.println("count:"+count);
					buffer.clear();
				}
			}
			s = System.currentTimeMillis() - s;
			System.out.println( "耗时:"+s+","+getString( md5.digest() ) );
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if( fStream!=null )
					fStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}


 

解决办法是File 类的lastModified方法(最佳)

 

	private String getHash(String fp){
		File file = new File(fp);
		return String.valueOf(file.lastModified());
	}


 

 

对于lastModified来说,针对file是文件时,且修改的是其内容才可以,否则取到的long值是一样的(如只修改文件/文件夹的名称)。

所以如何判断不能版本更新不能单单依靠File的lastModifyed方法。

可以取lastModifyed的值加上文件/文件夹的名字作为判断的依据。

 

 

 附加文章:MessageDigest的使用

http://blog.csdn.net/eclipser1987/article/details/5158784

http://blog.csdn.net/eclipser1987/article/details/5159106

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值