2013-05-30 41 views
3

我需要从test.jar文件中读取/test/a.xml的内容(它们都是变量,当然不是常量)。什么是最简单的方法呢?如何从JAR档案中读取文件?

File file = new File("test.jar"); 
String path = "/test/a.xml"; 
String content = // ... how? 
+0

是您的应用程序还从'test.jar'运行? – Pshemo

+0

不,我的应用程序没有从test.jar运行 – yegor256

+0

您使用的是Java 7吗? –

回答

4

如何:

JarFile file = new JarFile(new File("test.jar")); 
JarEntry entry = file.getJarEntry("/test/a.xml"); 
String content = IOUtils.toString(file.getInputStream(entry)); 
2

使用ZipInputStream并搜索您的请求文件。

FileInputStream fis = new FileInputStream(args[0]); 
ZipInputStream zis = new ZipInputStream(fis); 
ZipEntry ze; 

while ((ze = zis.getNextEntry()) != null) 
    if(ze.getName().equals("/test/a.xml") 
    { 
     //use zis to read the file's content 
    }