使用java.util.jar.JarOutputStream 以程式設計方式建立JAR 檔案看起來很簡單,但某些細微差別可能會導致意外問題。本文探討了這些未記錄的怪癖,並提供了用於建立有效 JAR 檔案的全面解決方案。
使用 JarOutputStream 時,遵守以下未記錄的規則至關重要:
下面是如何使用清單文件創建JAR 文件的詳細示例,解決了上述問題:
public void run() throws IOException {
// Prepare the manifest file
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
// Create a new JAROutputStream with the manifest
JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);
// Iterate over the source directory and add files to the JAR
add(new File("inputDirectory"), target);
// Close the JAROutputStream
target.close();
}
private void add(File source, JarOutputStream target) throws IOException {
// Prepare the entry path
String name = source.getPath().replace("\\", "/");
// Handle directories
if (source.isDirectory()) {
if (!name.endsWith("/")) {
name = "/";
}
// Create a directory entry with appropriate timestamps
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
// Recursively add files within the directory
for (File nestedFile : source.listFiles()) {
add(nestedFile, target);
}
}
// Handle files
else {
// Create a file entry with appropriate timestamps
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
// Read and write the file contents to the JAR
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();
}
}
}
透過遵循這些準則,您現在可以自信地以程式設計方式建立有效的 JAR 文件,確保您可以按預期存取其中包含的庫和其他資源。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3