微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。