Jar Manifest Attributes Read
Write a manifest into a jar with JarOutputStream and read its attributes back with JarFile, the metadata version reporting relies on.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
public class JarManifestReader {
public static void main(String[] args) throws IOException {
Path jar = Files.createTempFile("app-", ".jar");
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.put(Attributes.Name.MANIFEST_VERSION, "1.0");
main.put(new Attributes.Name("Implementation-Version"), "2.4.1");
main.put(new Attributes.Name("Build-Jdk-Spec"), "21");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar), manifest)) {
out.putNextEntry(new java.util.zip.ZipEntry("app/main.txt"));
out.write("hello".getBytes());
}
// JarFile 直接读元数据,不必解包整个归档
try (JarFile jarFile = new JarFile(jar.toFile())) {
Attributes attrs = jarFile.getManifest().getMainAttributes();
System.out.println("version: " + attrs.getValue("Implementation-Version"));
System.out.println("jdk: " + attrs.getValue("Build-Jdk-Spec"));
}
Files.delete(jar);
}
}How it works
Count the class JarManifestReader as the entire surface area of Jar Manifest Attributes Read.
The try-with-resources form guarantees each declared resource is closed even when the body throws.
Using it
The demo output is labeled (version:, jdk:), so every printed line maps back to its originating operation.
Key statements
main.put(new Attributes.Name("Implementation-Version"), "2.4.1");
out.putNextEntry(new java.util.zip.ZipEntry("app/main.txt"));
Attributes attrs = jarFile.getManifest().getMainAttributes();
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Jar Manifest Attributes Read print when run?
- No setup needed: run the file and look for labeled lines like `version:`, `jdk:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.