我已经试过许多方法来从正确的罐子访问索引的单元测试。我的问题是,它似乎是阅读谈到第一个jar文件,而不是一个对我的课。这是我最新的尝试
InputStream is = Test.class.getResourceAsStream("/META-INF/MANIFEST.MF");
try {
if (is == null) {
System.out.println("null no input stream");
} else {
Manifest manifest = new Manifest(is);
Attributes attributes = manifest.getMainAttributes();
v = attributes.getValue("Test");
System.out.println("Test="+v);
v = attributes.getValue("Created-by");
System.out.println("By="+v);
}
} catch (IOException e) {
System.out.println("error");
} finally {
if (is != null) {
is.close();
}
}
而这些结果
Test=null
By=1.6.0_18 (Sun Microsystems Inc.)
我想用MANIFEST.MF
有Test
的值,所以我知道这是读错文件
有谁知道我怎么可以指定其中包含了单元测试使用清单文件中的罐子?
这是我想出了.....注意到你的类/对象替换HTMLDocumen
t。
HTMLDocument htmlDoc = new HTMLDocument();
try
{
JarFile jarfile = new JarFile(htmlDoc.getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
// Get the manifest
Manifest manifest = jarfile.getManifest();
Map<String,Attributes> msa = manifest.getEntries();
for (String key : msa.keySet())
{
System.out.println("KEY: " + key);
Attributes a = msa.get(key);
for (Object k : a.keySet())
{
System.out.println(k + " - " + a.get(k));
}
}
}
catch (IOException e)
{
System.out.println("error");
}
你可以用这个试试:
URLClassLoader classLoader = (URLClassLoader) getClass().getClassLoader();
try {
URL url = classLoader.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
// add your code
...
} catch (IOException E) {
// handle exception
}
您可以访问包含类的jar:
InputStream in = MyClass
.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.openStream();
我在你的代码改变了这一行,并得到了相同的结果,虽然,you might want to walk and read the whole jar your self直到找到清单文件,然后从那里阅读。
“测试”是不是main attribute。
尝试getEntries()并期待您的自定义属性那里。
这是我最后所采用的方法...
String path = Test.class.getProtectionDomain()
.getCodeSource().getLocation().getPath();
path = path.replace("classes/", "");
URL url = null;
try {
url = new URL("jar:file:"+path+"test.jar!/");
JarURLConnection jarConnection = null;
try {
jarConnection = (JarURLConnection)url.openConnection();
Manifest manifest = jarConnection.getManifest();
java.util.jar.Attributes manifestItem = manifest.getMainAttributes();
System.out.println(manifestItem.getValue("Test"));
System.out.println(manifestItem.getValue("Implementation-Version"));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} catch (MalformedURLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
它与所有的路径操作和罐子名的硬编码非常脏......难道这件事情?再一次感谢你!