使用 JarOutputStream 創建 JAR 文件
要以編程方式生成 JAR 文件,通常使用 JarOutputStream。但是,必須避免 JarOutputStream 中某些未記錄的怪癖:
1。以斜杠結尾的目錄:
JAR 文件中的目錄名稱必須以“/”斜杠結尾。
2.使用正斜杠的路徑:
在路徑中使用正斜杠“/”,而不是反斜杠“\”。
3。條目名稱中沒有前導斜杠:
條目名稱不應以“/”斜杠開頭。
更正示例代碼:
以下更正後的代碼使用清單文件構造一個有效的JAR 文件:
public void run() throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);
add(new File("inputDirectory"), target);
target.close();
}
private void add(File source, JarOutputStream target) throws IOException {
String name = source.getPath().replace("\\", "/");
if (source.isDirectory()) {
if (!name.endsWith("/")) {
name = "/";
}
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
for (File nestedFile : source.listFiles()) {
add(nestedFile, target);
}
} else {
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1) {
break;
}
target.write(buffer, 0, count);
}
target.closeEntry();
}
}
}
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3