3

I need to read the content of /test/a.xml from a test.jar file (they are both variables, of course, not constants). What is the simplest way to do it?

File file = new File("test.jar");
String path = "/test/a.xml";
String content = // ... how?
yegor256
  • 102,010
  • 123
  • 446
  • 597

2 Answers2

7

How about this:

JarFile file = new JarFile(new File("test.jar"));
JarEntry entry = file.getJarEntry("/test/a.xml");
String content = IOUtils.toString(file.getInputStream(entry));
yegor256
  • 102,010
  • 123
  • 446
  • 597
2

Use a ZipInputStream and search for your requested file.

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
   }
Jimmy T.
  • 4,033
  • 2
  • 22
  • 38