java zip md5_通过java.util.zip.ZipFile解析zip文件,遍历Entry生成新的Zip文件,新旧两个文件的MD5值不一样...

本文展示了如何使用Java修改ZIP文件并尝试保持MD5值不变。通过遍历ZipEntry并直接复制内容到新文件,然后对比源文件和目标文件的MD5值,来探讨这一操作的可能性。
摘要由CSDN通过智能技术生成

修改zip文件,删除ZipEntry,再还原ZipEntry后,想保持MD5值一样,可以采取直接修改Zip文件内容的方式。

zip文件格式参考

https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT

import java.io.*;

import java.security.NoSuchAlgorithmException;

import java.util.Enumeration;

import java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

import java.util.zip.ZipOutputStream;

public class ZipCopyDemo {

public static void main(String[] args) throws IOException {

File src = new File("d:/tmp/junit-4.12.jar");

File dest = new File("d:/tmp/junit-4.12-2.jar");

ZipFile zipSrc = new ZipFile(src);

ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));

Enumeration srcEntries = zipSrc.entries();

while (srcEntries.hasMoreElements()) {

ZipEntry srcentry = (ZipEntry) srcEntries.nextElement();

ZipEntry destEntry = new ZipEntry(srcentry);

zos.putNextEntry(destEntry);

org.apache.commons.io.IOUtils.copy(zipSrc.getInputStream(srcentry), zos);

zos.closeEntry();

}

zos.finish();

zos.close();

zipSrc.close();

System.out.println(src.getAbsolutePath() + "\t md5=" + getMD5(readcontent(src)));

System.out.println(dest.getAbsolutePath() + "\t md5=" + getMD5(readcontent(dest)));

}

private static byte[] readcontent(File file) throws IOException {

try (InputStream in = new FileInputStream(file);) {

return toByteArray(in, (int) file.length());

}

}

public static byte[] toByteArray(InputStream input, int size) throws IOException {

if (size == 0) {

return new byte[0];

}

byte[] data = new byte[size];

int offset = 0;

int readed;

while (offset < size && (readed = input.read(data, offset, size - offset)) != -1) {

offset += readed;

}

if (offset != size) {

throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size);

}

return data;

}

public static String getMD5(byte[] source) {

String s = null;

char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',

'a', 'b', 'c', 'd', 'e', 'f'};

try {

java.security.MessageDigest md = java.security.MessageDigest

.getInstance("MD5");

md.update(source);

byte tmp[] = md.digest();

char str[] = new char[16 * 2];

int k = 0;

for (int i = 0; i < 16; i++) {

byte byte0 = tmp[i];

str[k++] = hexDigits[byte0 >>> 4 & 0xf];

str[k++] = hexDigits[byte0 & 0xf];

}

s = new String(str);

} catch (NoSuchAlgorithmException e) {

throw new RuntimeException(e);

}

return s;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值