java原生和SpringBoot读取jar包中MANIFESTMF的方式
Java原生方式读取jar包中MANIFEST.MF的方式如下:
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class Main {
public static void main(String[] args) {
try {
JarFile jarFile = new JarFile("path/to/your/jar/file.jar");
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
String version = attributes.getValue("Implementation-Version");
String createdBy = attributes.getValue("Created-By");
System.out.println("Version: " + version);
System.out.println("Created by: " + createdBy);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Spring Boot的方式可以使用org.springframework.boot.loader.JarFile类来读取MANIFEST.MF的内容。需要添加Spring Boot的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader</artifactId>
<version>2.5.2</version>
</dependency>
然后使用以下代码读取MANIFEST.MF的内容:
import org.springframework.boot.loader.JarFile;
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class Main {
public static void main(String[] args) {
try {
JarFile jarFile = new JarFile("path/to/your/jar/file.jar");
Manifest manifest = jarFile.getManifest();
Attributes attributes = manifest.getMainAttributes();
String version = attributes.getValue("Implementation-Version");
String createdBy = attributes.getValue("Created-By");
System.out.println("Version: " + version);
System.out.println("Created by: " + createdBy);
} catch (IOException e) {
e.printStackTrace();
}
}
}
需要注意的是,Spring Boot的方式依赖于Spring Boot的特性,适用于使用Spring Boot打包的jar文件
原文地址: https://www.cveoy.top/t/topic/iUQ3 著作权归作者所有。请勿转载和采集!