简体   繁体   中英

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:)

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM