Samuel E.
Samuel E.

Reputation: 83

Loading files from subfolder of the resources folder in Java

I have a problem loading files from a subfolder in the resources folder of my IntelliJ Java 15 Gradle Project...

A representation of my project structure:

src/main/
├── java/
│   ├── AllMyClasses.java ... ... ...
│   └── module-info.java
└── resources/
    ├── text.txt
    └── img/
        └── favicon.png

And the relevant snippet of my code:

URL file = ClassLoader.getSystemResource("img/favicon.png");
URL file1 = ClassLoader.getSystemResource("text.txt");
System.out.println(file);
System.out.println(file1);

The output:

null
file:/C:/Users/MyUser/IdeaProjects/MyProject/build/resources/main/text.txt

Why does java only recognize the files DIRECTLY in the resources folder and not those in subfolders? How can I make my program also recognize those inside a subfolder?

Thanks to everyone who can help :)

Upvotes: 4

Views: 1792

Answers (2)

NameThatDisplays
NameThatDisplays

Reputation: 50

I am not sure why your version is not working but here is what I use:

getClass().getResourceAsStream("/img/favicon.png");

Note: '/' in "/img" is necessary if your class is not in a default package (which it should not be)

Upvotes: 1

Nishant Gupta
Nishant Gupta

Reputation: 21

I believe if you make use of either of the two as below will solve your issue.

  1. InputStream in = FileInputStream(PathOfYourFile)
  2. API's available in Paths class available in java.nio.file package.

Upvotes: 0

Related Questions