1

In my code I have need populate a JComboBox by scanning a directory and feeding the results to the Combo box.

I do this as follows

File folder = new File("src/profiles");
for (final File fileEntry : folder.listFiles())             
         list.add(fileEntry.getName().substring(0, fileEntry.getName().length()-5));

This works just fine in Eclipse, but once I export to a runnable jar it throws a null pointer exception on my for loop. I'm guessing this is because the folder file can't be made/found since the structure is no longer the same. I've checked the jar with 7zip and the profiles dir is there. It's at the root of the jar, but even if I change "src/profiles" to "profiles" or "\profiles" it still throws the same null pointer exception error

The Directory structure looks something like this for reference

    Project
       bin
          name
          images
          profiles
       src
          name
              this.java
              that.java
          images
          profiles
              profile1.json
              profile2.json

Anyone either know of a way still make this work after exporting to a jar? either by getting the folder in a different way or scanning the directory in another way?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MRedgate
  • 11
  • 1
  • 2
    Study the concept of "resources" in Java – Jim Garrison Jul 05 '18 at 18:28
  • *"**File** gives null pointer after being exported to a **jar** .. In my code I have need populate a JComboBox by scanning a **directory** and feeding the results to the Combo box."* The problem here is that a Jar contains neither files nor directories, only resources and their paths. The most robust approach to solve this is to create a list of resources at build time, and write that list into a resource in the Jar at a known location. – Andrew Thompson Jul 06 '18 at 05:12

1 Answers1

0

If you want to look up for resources in the application's classpath (inside the jar in your case) then you can use Java's classloader resources features.

Here's an example: Get a list of resources from classpath directory

marciopd
  • 132
  • 11