2

I want to do an import that looks inside a folder and cycles through the files found there and then imports stuff.

In my project I have the folder under src/main/resources but in the actual jar it will be packed as a folder on the root (not inside a resources folder) so I don't know how to get the folder path giving only it's name.

I have tried via getResources and passed the folder name as string and also tried something like File folderPath = new File("./import") (to use the relative path) but that didn't work either.

The difference between the suggested post and mine is that in there that folder path is known(it is a fixed hardcoded location) I need to find that based on class loading or something similar

Below it's the code I am using

public static final String IMPORT_FILES_LOCATION ="import"; //folder name
Enumeration<URL> folderURL = null;
    try {
        folderURL = getClass().getClassLoader().getResources(IMPORT_FILES_LOCATION);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (folderURL != null && folderURL.hasMoreElements()) {
        File folderFile = new File(folderURL.nextElement().getPath());
        File[] filesToImport = folderFile.listFiles();
        if(filesToImport.length > 0) {
            for (File fileToImport : filesToImport) {
                System.out.println("import stuff");
            }
        }
    }

Any ideas/suggestions ?

Thanks

Taky
  • 5,284
  • 1
  • 20
  • 29
Viocartman
  • 153
  • 3
  • 14
  • Possible duplicate of [Read all files in a folder](http://stackoverflow.com/questions/1844688/read-all-files-in-a-folder) – António Ribeiro Mar 10 '16 at 14:29
  • 1
    His problem is slightly more complicated than that given that the folder is not necessarily a known path on the HD, but rather a classpath resource. OP, you were on the right track with `getResources()`. Could you post the code that you were using when you tried this? – rmlan Mar 10 '16 at 14:30
  • As mlan mentioned my problem is different. If you look at the other post it knows the folder path (it is hardcoded). I need a solution that find that folder based on its name – Viocartman Mar 10 '16 at 14:58
  • What is not working about this? Do you get an exception, or is there simply no output? Try using `getResource()` instead. – rmlan Mar 10 '16 at 17:35
  • The folderURL has no elements. If i use getResource i have the same problem, the field remains null Should i use "/import" or maybe "./import" ? – Viocartman Mar 11 '16 at 08:03

1 Answers1

0

I solved this issue by adding a config file property where the import folder location is stored. The user is prompted to enter a location and if that field is left empty a default is provided(we have a GUI for installing the module)

It still doesn't solve the initial issue but it's a workaround that works. Hope it helps

Viocartman
  • 153
  • 3
  • 14