我有2个zip文件,其中包含一个包含2个文本文件的文件夹。
我的第一个zip文件:
fodler1
|_ file1.txt
|_ file2.txt
我的第二个zip文件:
folder1
|_ file1.txt
|_ file2.txt
两个zip文件都作为字节数组传递。我正在研究比较这两个zip文件中的每个条目。因此,如果文件名称相同但内容不同,则该函数应返回false。这是我的方法:
private void compareZip (byte[] zip1, byte[] zip2) throws IOException{
ZipInputStream zipStream1 = new ZipInputStream(new ByteArrayInputStream(zip1));
HashMap <String, InputStream> allEntries1 = new HashMap<String, InputStream>();
ZipEntry entry1 = null;
//Save InputStream of every entry in zip1
while ((entry1 = zipStream1.getNextEntry()) != null) {
allEntries1.put(entry1.getName(), zipStream1);
zipStream1.closeEntry();
}
ZipInputStream zipStream2 = new ZipInputStream(new ByteArrayInputStream(zip2));
HashMap <String, InputStream> allEntries2 = new HashMap<String, InputStream>();
ZipEntry entry2 = null;
//Save InputStream of every entry in zip2
while ((entry2 = zipStream2.getNextEntry()) != null) {
allEntries2.put(entry2.getName(), zipStream2);
zipStream2.closeEntry();
}
//Returns true although files have different content
isEqual(allEntries1.get("folder1/file1.txt"), allEntries2.get("folder1/file1.txt"));
zipStream1.close();
zipStream2.close();
}
函数isEqual
比较2个InputStreams:
private static boolean isEqual(InputStream i1, InputStream i2)
throws IOException {
ReadableByteChannel ch1 = Channels.newChannel(i1);
ReadableByteChannel ch2 = Channels.newChannel(i2);
ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);
try {
while (true) {
int n1 = ch1.read(buf1);
int n2 = ch2.read(buf2);
if (n1 == -1 || n2 == -1) return n1 == n2;
buf1.flip();
buf2.flip();
for (int i = 0; i < Math.min(n1, n2); i++)
if (buf1.get() != buf2.get())
return false;
buf1.compact();
buf2.compact();
}
} finally {
if (i1 != null) i1.close();
if (i2 != null) i2.close();
}
}