繁体   English   中英

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

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

在我的SpringBoot项目中,我想读取位于以下位置的图像文件:

在此处输入图片说明

我试过了:

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

和:

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

但结果为空。

编辑:这工作

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

}

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

你可以试试这个

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

因为我们可以从任何地方访问静态文件夹

你有没有尝试过

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

您可以使用this.getClass().getResource("/static/images").getFile(); 获取文件夹位置,然后附加文件名以获取文件位置。

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