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.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().
In the above code snippet, we used the current class to load a file using getResourceAsStream method and passed the absolute path of the file to load. The same method is available on a ClassLoader instance as well: ClassLoader classLoader = getClass(). getClassLoader(); InputStream inputStream = classLoader.
(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...
When I packaged the jar file, I am including several xml files inside it in a folder named data
data/listOfXML.txt
at the same time.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With