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