我在src/main/resources/static/css/下有一个名为my.css的文件,我试图将其作为字符串加载,但我无论如何也无法让Spring找到这个应该已经静态加载到类路径中的文件。
private String getCss(String cssFileName) {
try {
File file = new ClassPathResource("classpath:" + cssFileName + ".css").getFile();
return new String(Files.readAllBytes(Paths.get(file.getPath())));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "css not found";
}
}我尝试过各种webconfigs、资源加载器、路径和模式,但我就是不能正常工作。如何在我的资源中查找文件?我希望是某种Resources.getResource("name.type")类型的东西,它已经有了一个树,其中列出了资源文件夹中的所有资源。
发布于 2019-05-31 18:51:06
使用@pandaadb的注释和Spring的自动连接功能来获取ResourceLoader类的实例:
@Controller
public class Controller {
@Autowired private ResourceLoader loader;
private String getCss(String cssFileName) {
try {
File file = loader.getResource("classpath:/static/css/" + cssFileName + ".css").getFile();
return new String(Files.readAllBytes(Paths.get(file.getPath())));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "css not found";
}
}ResourceLoader使用src/main/resources文件夹作为"classpath:“搜索的根目录,因此只需从该位置添加完整路径即可。不要直接使用classpathloader,它会以某种方式自动转换为基于给定前缀的类。这段代码现在可以找到文件,读取它并将其转换为字符串。
发布于 2019-05-31 18:27:41
我记得当我需要加载这个xml/json文件时遇到了同样的问题。下面是我如何解决这个问题的-
String sorting;
this.sorting = org.apache.commons.io.IOUtils.toString((getClass().getClassLoader().getResource("order.json")),
StandardCharsets.UTF_8.name());https://stackoverflow.com/questions/56393224
复制相似问题