简体   繁体   English

从Java中的src / main / resources访问静态文件

[英]Access static files from src/main/resources in Java

In my SpringBoot project I would like to read an image file located in: 在我的SpringBoot项目中,我想读取位于以下位置的图像文件:

在此处输入图片说明

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(); 您可以使用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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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