简体   繁体   中英

Access static files from src/main/resources in Java

In my SpringBoot project I would like to read an image file located in:

在此处输入图片说明

I tried:

URL url = getClass().getResource("android.png");
File f = new File(url.getPath());

and:

URL url = getClass().getResource("static/images/android.png");
File f = new File(url.getPath());

but the result is null.

EDIT: this worked

try {
   File file = new ClassPathResource("static/images/android.png").getFile();    
} catch (IOException e) {

}

如果您使用的是Spring,则最好使用内置的ClassPathResource类来访问类路径中的文件。

You can try this

File file = new ClassPathResource("/images/android.png").getFile();

because we can access static folder from anywhere

你有没有尝试过

ClassLoader.getSystemResourceAsStream("/static/images/android.png");

you can use this.getClass().getResource("/static/images").getFile(); to get the folder location and then append with the file name to get the file location.

Example

String path=this.getClass().getResource("/static/images").getFile();
File File f = new File(path+"/​android.png");

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