小编Mar*_*icz的帖子

Spring Boot中如何读写文件

我在保存文件并在生成 .war 文件后下载它们时遇到问题。在应用程序中管理员按下按钮后,我需要处理许多文件的生成。这些文件是使用使用 POST 方法发送的部分代码生成的,第二部分来自数据库。文件有数百/数千个,不可能手动完成。管理员不时生成文件。用户应该能够从应用程序下载这些文件。当我在 IntelliJ 中运行应用程序时,应用程序可以访问磁盘上的文件夹,因此以下代码有效:(后端类的一部分,负责将文件保存在路径中)

    private void saveTextToFile(String text, String fileName) {
        String filePathAndName = "/static/myFiles/" + fileName+ ".txt";
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(".").getFile() + filePathAndName );
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            PrintWriter printWriter = new PrintWriter(fileWriter);
            printWriter.print(text);
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

该文件保存在文件夹中: C:\Users...\myProject\target\classes\static。(这是百里香中生成的文件的链接)

<html xmlns:th="http://www.thymeleaf.org">

<a th:href="@{|/myFiles/${thisIsMyFileName}|}">Download file</a>
</html>
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我生成 .war 文件并运行它时,这些文件没有保存在应用程序的“资源”文件夹中。因此,用户无法通过 thymeleaf 生成的链接下载该文件。

java spring thymeleaf spring-boot

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

java ×1

spring ×1

spring-boot ×1

thymeleaf ×1