1

I have recently converted an existing Java-application into a Maven-application which is generating a MyJar.jar file. Also I've included the application's resource xml files inside a folder named "MyXml" and packaged it in that jar.

Now I need to read that list of xml files within that folder inside the jar and iterate over the files. I am using linux environment, and my java code is getting Null pointer exception while trying to access that folder inside the jar.

The folder path in the Jar is :

String folderPath = "app/tools/Tool1/MyJar.jar/MyXml/";

The java code which is throwing exception is:

final File folder = new File(folderPath);
for (final File fileEntry : folder.listFiles()) {
    if (fileEntry.getName().toLowerCase().endsWith(".xml")) {
        System.out.println("Xml File name : "+fileEntry.getName());
    }
}

In the for-loop , "folder" object is getting null and throwing exception. Can't we mention a file-path inside a "jar" using java?

I saw some examples from Here, but there it's reading only particular file from jar, not the list of files. Any suggestion will be helpful.

Jerry
  • 281
  • 4
  • 21
  • 1
    The path you are using is not a valid path, this is a valid path `app/tools/Tool1/MyJar.jar` but the bit on the end is not. You will need to use a library that can open the contents of an archive/jar file, or you will need to extract the contents from the jar file before you attempt to read the xml files `app/tools/Tool1/extractedFiles/MyXml/` – sorifiend Aug 20 '20 at 04:40
  • You can make use of the NIO API `FileSystem` like shown here: https://stackoverflow.com/a/37413531/1270000 – sorifiend Aug 20 '20 at 04:50
  • Okay, so without extracting the jar, I cannot read the internal resource files anyhow. Let me try to extract the file using **linux shell script** then. Hopefully it will be extracted in the same folder location that of the jar. I will reply, if it works. Thanks. – Jerry Aug 20 '20 at 05:14
  • You can read the contents of a jar/archive without extracting it, you just need to use the correct library/API. But a more simple approach is to extract it first, then you can use regular file paths. – sorifiend Aug 20 '20 at 05:17
  • 1
    Yes, I extracted first using shell-script and access like regular files. Thanks for your suggestion. Initially I thought without extracting I can use the internal folders and files. Anyway thanks. – Jerry Aug 21 '20 at 05:24

0 Answers0