通过了解罐子的名称和位置,有没有办法抓住它的清单并获得它的属性?
我有以下代码:
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;
答案 0 :(得分:2)
大多数标准属性可以直接从Package类中读取:
String version = MyApplication.class.getPackage().getSpecificationVersion();
要读取自定义atttributes,请不要使用java.io.File类。您永远不应假设网址是file:
网址。
相反,您可以使用JarInputStream:
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);
或者,您可以通过构建JarURLConnection复合网址直接阅读清单:
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);
请注意ProtectionDomain.getCodeSource() can return null。在应用程序中指定版本号的更好方法是将其放在清单的Specification-Version或Implementation-Version属性中,以便可以从Package方法中读取它。请记住,虽然Implementation-Version是一个自由格式的字符串,a Specification-Version value must consist of groups of ASCII digits separated by periods。
另一种方法是创建一个数据文件并将其包含在.jar中,然后您可以使用Class.getResource或Class.getResourceAsStream阅读:
Properties props = new Properties();
try (InputStream stream = MyApplication.class.getResourceAsStream("application.properties")) {
props.load(stream);
}
String revisionNumber = props.getProperty("version");