Java 获取一个Jar文件';通过了解它来表现它';s位置
通过知道jar的名称和位置,有没有办法获取它的清单并获取它的属性 我有以下代码:Java 获取一个Jar文件';通过了解它来表现它';s位置,java,maven,jar,manifest,Java,Maven,Jar,Manifest,通过知道jar的名称和位置,有没有办法获取它的清单并获取它的属性 我有以下代码: public static String readRevision() throws IOException { URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation(); String jarLocation = new File(jarLocationUrl.toString()
public static String readRevision() throws IOException {
URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
String jarFilename = new File(jarLocationUrl.toString()).getAbsoluteFile().getName();
// This below is what I want to get from the manifest
String revision = manifest.getAttributes("Revision-Number").toString();
return revision;
大多数标准属性可以直接从类中读取:
要读取自定义属性,请不要使用java.io.File类。永远不要假设URL是文件:
URL
相反,您可以使用:
或者,您可以通过构造复合URL直接读取清单:
URL manifestURL = new URL("jar:" + jarLocationUrl + "!/META-INF/MANIFEST.MF");
Manifest manifest;
try (InputStream manifestSource = manifestURL.openStream()) {
manifest = new Manifest(manifestSource);
}
Attribute.Name name = new Attribute.Name("Revision-Number");
String revisionNumber = (String) manifest.getMainAttributes().get(name);
请注意。在应用程序中指定版本号的更好方法是将其放在清单的Specification version或Implementation version属性中,这样就可以从包方法中读取它。请记住,虽然实现版本是一个自由格式的字符串
另一种方法是简单地创建一个数据文件并将其包含在.jar中,然后可以使用或读取该文件:
,
Manifest manifest;
try (JarInputStream jar = new JarInputStream(ljarLocationUrl.openStream())) {
manifest = jar.getManifest();
}
Attribute.Name name = new Attribute.Name("Revision-Number");
String revisionNumber = (String) manifest.getMainAttributes().get(name);
URL manifestURL = new URL("jar:" + jarLocationUrl + "!/META-INF/MANIFEST.MF");
Manifest manifest;
try (InputStream manifestSource = manifestURL.openStream()) {
manifest = new Manifest(manifestSource);
}
Attribute.Name name = new Attribute.Name("Revision-Number");
String revisionNumber = (String) manifest.getMainAttributes().get(name);
Properties props = new Properties();
try (InputStream stream = MyApplication.class.getResourceAsStream("application.properties")) {
props.load(stream);
}
String revisionNumber = props.getProperty("version");