Is there any way i can read the contents of a jar file. like i want to read the manifest file in order to find the creator of the jar file and version. Is there any way to achieve the same.
Is there any way i can read the contents of a jar file. like i want to read the manifest file in order to find the creator of the jar file and version. Is there any way to achieve the same.
Achieve the attributes in this simple way
public static String getMainClasFromJarFile(String jarFilePath) throws Exception{
// Path example: "C:\\Users\\GIGABYTE\\.m2\\repository\\domolin\\DeviceTest\\1.0-SNAPSHOT\\DeviceTest-1.0-SNAPSHOT.jar";
JarInputStream jarStream = new JarInputStream(new FileInputStream(jarFilePath));
Manifest mf = jarStream.getManifest();
Attributes attributes = mf.getMainAttributes();
// Manifest-Version: 1.0
// Built-By: GIGABYTE
// Created-By: Apache Maven 3.0.5
// Build-Jdk: 1.8.0_144
// Main-Class: domolin.devicetest.DeviceTest
String mainClass = attributes.getValue("Main-Class");
//String mainClass = attributes.getValue("Created-By");
// Output: domolin.devicetest.DeviceTest
return mainClass;
}
public void processManifestFile() {
String version = this.getClass().getPackage().getImplementationVersion();
LOG.info("Version: {}", version);
Path targetFile = Paths.get(System.getProperty("user.home"), "my-project", "MANIFEST.MF");
try {
URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
JarFile jarFile = new JarFile(url.getFile());
Manifest manifest = jarFile.getManifest();
try(FileWriter fw = new FileWriter(targetFile.toFile())) {
manifest.getMainAttributes().entrySet().stream().forEach( x -> {
try {
fw.write(x.getKey() + ": " + x.getValue() + "\n");
LOG.info("{}: {}", x.getKey(), x.getValue());
} catch (IOException e) {
LOG.error("error in write manifest, {}", e.getMessage());
}
});
}
LOG.info("Copy MANIFEST.MF to {}", targetFile);
} catch (Exception e) {
LOG.error("Error in processing MANIFEST.MF file", e);
}
}