How to Read files in an folder inputstream
Asked Answered
M

2

6

I have a Jar file that I have created using 3rd party library. When I packaged the jar file, I am including several xml files inside it in a folder named data

data
    - file1.xml
    - file2.xml
    - file3.xml

Now, I wanted to read the folder inside the jar file and as per the documentation of the 3rd party library I could get the classloader and read the folder as inputstream like this.

ClassLoader clsLoader = myService.getClassLoader();
InputStream accountsStream =  clsLoader.getResourceAsStream("data");

Question is, how can I list all the files from the inputstream and parse it one by one?

Thanks

EDIT Added Info:

How do I access resources that I put into my service or module archive file?

http://axis.apache.org/axis2/java/core/faq.html#b1

Sorry, the question should have been specific to Apache Axis but I am confused a little bit if it is a Java specific question also.

After getting an inputstream to a folder using the classloader, how do I list all the files into that folder and read it one by one?

The steps in my code would inlcude.

  1. Get an inputstream into the folder
  2. List all files from that inputstream
  3. Read it one by one
Mateusz answered 10/1, 2012 at 2:38 Comment(2)
What's the 3rd party library you're using, and/or can you give is a link to its documentation as well?Disposal
Hi, its Apache Axis. axis.apache.org/axis2/java/core/faq.html#b1 When I package my service, I wanted it to access the folder inside the module archive. ThanksMateusz
P
2

(Sorry - ignore my answer - here's a better one:)

How do I list the files inside a JAR file?

This is a rather fragile solution, but you could just read your own jar file:

File file = new File(System.getProperty("user.dir") + "/jarname.jar");
JarFile jfile = new JarFile(file);
Enumeration e = jfile.entries();
while (e.hasMoreElements()) {
   ZipEntry entry = (ZipEntry)e.nextElement();
   String path = entry.getName();
   if(path.startsWith("/path/within/jarfile/") && path.endsWith(".xml")) {
      MyClass.loadResourceAsStream(path);
   }
}

What makes it fragile is that it depends on your jarfile having a particular name, not being inside another jarfile, and so on. I'm sure there's a more elegant way...

Preshrunk answered 10/1, 2012 at 2:48 Comment(0)
J
2

When I packaged the jar file, I am including several xml files inside it in a folder named data

  1. Also include a list called (e.g.) data/listOfXML.txt at the same time.
  2. Obtain the list as a resource.
  3. Read the list to get the names of the XML files
Jdavie answered 10/1, 2012 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.