如何使用 Java 在 heroku/docker 中创建临时目录?

问题描述

我正在尝试创建一个临时文件并生成一个文件名,然后保存一个多部分文件。我正在使用 Spring Boot,以下代码在本地运行。但是在 heroku 或 docker 中,它正在抛出 FileNotFoundException;那么如何在 docker/heroku 中创建一个临时目录并将文件保存在该临时目录中呢? 或者将 multipart 文件保存到服务器中的临时文件夹的最佳方法是什么?有人可以帮助我吗?提前致谢。

File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")),"files");

   if (!tempDirectory.exists()) {
       tempDirectory.mkdir();
   }

String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.pdf").getAbsolutePath();

解决方法

 File tempDirectory = new File(new File(System.getProperty("java.io.tmpdir")),"files");
        if(tempDirectory.exists()){
            System.out.println("something");
        }else{
            tempDirectory.mkdirs();
        }

        File file = new File(tempDirectory.getAbsolutePath()+"/abcd.txt");
        if(!file.exists()){
            file.createNewFile();
        }
        String file2= new File(tempDirectory.getAbsolutePath()+"/something.txt").getAbsolutePath();


        System.out.println(file2);

在我的最后工作完全正常。您可能遇到的唯一问题是

String filePath = new File(tempDirectory.getAbsolutePath() + "/temp.exe").getAbsolutePath();

这不会在您创建的临时目录中创建文件。如果要将其保存在提到的目录中,它只会返回绝对路径。这可能是您收到 not found 错误的原因。尝试实际保存使用

file.transferTo(wherefileneedstobesavedlocation);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...