rakku
rakku

Reputation: 73

Not able to access files in resource folder

I have created a new module in Intellij with directory structure as follows:
new-module -> src -> main -> java -> config -> resources -> ConfigResources.java
new-module -> src -> main-> resources -> config -> resources -> config.properties

When I build my intellij project, I see that the resource file is being copied correctly to "out/production/resources" directory

Now when I try to access this file through following code, it returns null:
ConfigResources.class.getResourceAsStream("config.properties")

From what I have read from several other posts, the above code tries to load file from same path in resource folder, but it didn't work for me.

What else have I tried:

  1. ClassLoader.class.getResource()
  2. Copied the properties file to java directory itself, but after build classes folder contains the classes and the properties file is copied to resource folder
  3. I tried giving the relative path from resource folder but it didn't work either
  4. Manually copied the file to classes folder then it works(obviously!)

How can I access the resource file? (It's a gradle project and uses java 11) Do I need to set any configuration in intellij or need to include something in my build.gradle file?

Upvotes: 0

Views: 1882

Answers (2)

Alex Shepel
Alex Shepel

Reputation: 696

I had the same issue. Try to add an additional folder "foo" to the resources directory. Sounds a bit confusing, but it works.

new-module -> src -> main -> resources -> config -> resources -> foo -> config.properties

ConfigResources.class.getClassLoader().getResourceAsStream(foo/config.properties);

Upvotes: 1

Arun Kumar T
Arun Kumar T

Reputation: 66

List<Document> docs = new ArrayList<>();
JSONParser jsonParser = new JSONParser();
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream(collectionName+".json");

try (Reader reader = new InputStreamReader(is)) {
    // Read JSON file
    Object obj = jsonParser.parse(reader);
    JSONArray documentArray = (JSONArray) obj;
    // Iterate over documentArray
    documentArray.forEach(doc -> {
        Document document = Document.parse(doc.toString());
        docs.add(document);
    });
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ParseException e) {
    e.printStackTrace();
}
return docs;

I'm also face the same issue but i fixed like this to get data from the resource

Upvotes: 0

Related Questions