【问题标题】:Manually get the contents of a file in Spring boot 2在 Spring Boot 2 中手动获取文件的内容
【发布时间】:2019-05-31 10:20:22
【问题描述】:

我在 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";
    }
}

我尝试了各种 webconfig、资源加载器、路径和模式,但我就是无法让它工作。如何在我的资源中找到文件?我希望某种 Resources.getResource("name.type") 类型的东西已经有一棵树,其中列出了资源文件夹中的所有资源。

【问题讨论】:

  • 您是否尝试过类似的方法:ResourceLoader.class.getResourceAsStream("/static/css/my.css"); 其中ResourceLoader 是您的类路径中的任何类?

标签: java spring spring-boot spring-mvc file-io


【解决方案1】:

我记得当我需要加载这个 xml/json 文件时遇到了同样的问题。 这是我解决它的方法 -

String sorting;
this.sorting = org.apache.commons.io.IOUtils.toString((getClass().getClassLoader().getResource("order.json")),
                    StandardCharsets.UTF_8.name());

【讨论】:

  • 老实说,我写那段代码已经有一段时间了,但我记得这是我让它正常工作的唯一方法。因此,对您来说,要么是那个,要么是几个小时的研究。希望您可以使用 apache commons,并且此解决方案适合您
【解决方案2】:

使用@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 文件夹作为“类路径:”搜索的根目录,因此只需从该点添加整个路径即可。不要直接使用类路径加载器,它会根据给定的前缀以某种方式自动转换为一个。此代码现在找到文件,读取它并将其转换为字符串。

【讨论】:

    猜你喜欢
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多