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? 
4
  • Is your application also running from test.jar? Commented May 30, 2013 at 17:23
  • No, my application is not running from test.jar Commented May 30, 2013 at 17:24
  • Are you using Java 7? Commented May 30, 2013 at 17:27
  • You can try to adapt this example: javaworld.com/javaworld/javatips/javatip49/JarResources.java Commented May 30, 2013 at 17:29

2 Answers 2

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)); 
Sign up to request clarification or add additional context in comments.

Comments

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 } 

2 Comments

How to use zis to read the file's content?
@mendel when you're in that if you can use fis like a regular InputStream and it will give you the content of the file

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.