我一直在调试一些 jar 更新片段,我遇到了一个 zip/unzip 组合,它应该是相反的,但是当我在一个 jar 上尝试它时,即使所有文件都存在,它也失败了。谁能弄清楚这是哪里出错了?
SSCCE(无需编译):在这里下载!
package jarsscce;
import java.io.*;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
public class JarSSCCE {
public static void main(String[] args) throws IOException {
File testJar = new File("test.jar");
File testDir = new File("test");
File jarPack = new File("packed_test.jar");
unpack(testJar, testDir);
jar(testDir, jarPack);
}
public static void jar(File directory, File zip) throws IOException {
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(zip))) {
jar(directory, directory, jos);
}
}
private static void jar(File directory, File base, JarOutputStream jos) throws IOException {
File[] files = directory.listFiles();
byte[] buffer = new byte[1 << 12];
if (files.length == 0) {
JarEntry entry = new JarEntry(directory.getPath().substring(base.getPath().length() + 1) + File.separator);
jos.putNextEntry(entry);
} else {
for (int i = 0, n = files.length; i < n; i++) {
if (files[i].isDirectory()) {
jar(files[i], base, jos);
} else {
try (FileInputStream in = new FileInputStream(files[i])) {
JarEntry entry = new JarEntry(files[i].getPath().substring(base.getPath().length() + 1));
jos.putNextEntry(entry);
int read;
while ((read = in.read(buffer, 0, buffer.length)) != -1) {
jos.write(buffer, 0, read);
}
jos.closeEntry();
}
}
}
}
}
public static void unpack(File zip, File extractTo) throws IOException {
try (ZipFile archive = new ZipFile(zip)) {
Enumeration e = archive.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
File file = new File(extractTo, entry.getName());
if (entry.isDirectory() && !file.exists()) {
file.mkdirs();
} else {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try (InputStream in = archive.getInputStream(entry)) {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buffer = new byte[1 << 13];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
out.close();
}
}
}
}
}
}
编辑:通过Winrar查看存档信息,我可以看到Netbeans创建的test.jar根本没有压缩,程序创建的那个是。“主机操作系统”和“要提取的版本”值也不同。虽然我看不出这有什么意义。