Home > Enterprise >  How to read files from the sub folder of resource folder
How to read files from the sub folder of resource folder

Time:10-01

How to read files from the sub folder of resource folder.

I have some json file in resources folder like :

src 
    main
        resources 
            jsonData
                d1.json
                d2.json
                d3.json

Now I want to read this in my class which is

src 
    main
        java
            com
                myFile
                    classes 

here is what I am trying but getting failed.

File folder = new File("./src/main/java/resources/jsonData/");
        File[] listOfFiles = folder.listFiles();

        for (File file : listOfFiles) {
            if (file.isFile()) {
               // my operation of Data.
            }
        }

Not working then I am trying :

Resource resource = new ClassPathResource("classpath:jsonData/data1.json");
File folder = new File(resource.getURI());
File[] listOfFiles = folder.listFiles();

both of things are not working.

CodePudding user response:

You should be able to achieve this using getClass.GetResource()

File[] fileList = (new File(getClass().getResource("/exampleFolder").toURI())).listFiles();

  • Related