Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create temp directory in heroku/docker using Java?

I am trying to create a temp file and generate a file name and then save a multipart file. I am using Spring Boot and the following code is working in local. But in heroku or docker it is throwing FileNotFoundException; So how to create a temp directory and save a file inside that temp directory in docker/heroku? Or what is the best way to save multipart file to temp folder in server? Anybody can help me? Thanks in advance.

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();
like image 635
Abraham Arnold Avatar asked Dec 06 '25 03:12

Abraham Arnold


1 Answers

 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);

Works totally fine at my end. The only problem you might be having is

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

This doesn't create the file in the temp directory you have created. It just returns the absolute path if it was to be saved in the directory mentioned. This might be the reason you are getting not found error. Try actually saving by using

file.transferTo(wherefileneedstobesavedlocation);
like image 142
Bishal Gautam Avatar answered Dec 07 '25 17:12

Bishal Gautam