我花了太多的时间试图弄清楚这一点。这应该是最简单的事情,每个在jar中分发Java应用程序的人都必须处理它。
我只是想知道正确的方式来添加版本到我的Java应用程序,以便我可以在测试时访问版本信息,例如在Eclipse中调试并从jar中运行。
这是我在我的build.xml中的代码:
<target name="jar" depends = "compile">
<property name="version.num" value="1.0.0"/>
<buildnumber file="build.num"/>
<tstamp>
<format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}" />
<attribute name="Built-Date" value="${TODAY}" />
<attribute name="Implementation-Title" value="MyApp" />
<attribute name="Implementation-Vendor" value="MyCompany" />
<attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>
</manifest>
<jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" />
</target>
这将创建/META-INF/MANIFEST.MF,我可以在Eclipse中调试时读取这些值:
public MyClass()
{
try
{
InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(stream);
Attributes attributes = manifest.getMainAttributes();
String implementationTitle = attributes.getValue("Implementation-Title");
String implementationVersion = attributes.getValue("Implementation-Version");
String builtDate = attributes.getValue("Built-Date");
String builtBy = attributes.getValue("Built-By");
}
catch (IOException e)
{
logger.error("Couldn't read manifest.");
}
}
但是,当我创建jar文件时,它加载另一个jar的清单(大概是应用程序加载的第一个jar - 在我的例子中是activation.jar)。
另外,尽管所有正确的值都在清单文件中,但下面的代码不起作用。
Package thisPackage = getClass().getPackage();
String implementationVersion = thisPackage.getImplementationVersion();
发布于 2018-01-19 10:38:51
你可以在任意一个jar文件中获得一个任意类的清单而不需要解析类的url。只要找到你想要的jar中的资源,然后将连接转换为JarURLConnection。
如果你希望代码在类未捆绑到jar的情况下工作,请添加一个instanceof检查返回的URL连接的类型。解压后的类层次结构中的类将返回内部Sun FileURLConnection而不是JarUrlConnection。然后,你可以使用InputStream方法加载Manifest。
@Test
public void testManifest() throws IOException {
URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class");
JarURLConnection conn = (JarURLConnection) res.openConnection();
Manifest mf = conn.getManifest();
Attributes atts = mf.getMainAttributes();
for (Object v : atts.values()) {
System.out.println(v);
}
}
发布于 2018-01-19 11:37:31
你可以用这个:
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
你可以通过解析这个URL来找出清单中的哪个jar文件,然后通过getInputStream()读取URL来解析清单。
https://stackoverflow.com/questions/-100001435
复制相似问题