-1

Where is it advisable to store temporary files with Java?

I need to unzip files from the archive, do some checks and clean up if all tests would pass. I wrote the following method:

@BeforeAll
static void unzipToTemp() throws Exception {
    ClassLoader classLoader = FileParsingTest.class.getClassLoader();

String fileZip = "files/zip_example.zip";
File destDir = new File("files/temp");
byte[] buffer = new byte[1024];
try (
        InputStream inputStream = classLoader.getResourceAsStream(fileZip);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
) {
    ZipEntry entry;
    while ((entry = zipInputStream.getNextEntry()) != null) {
        File newFile = new File(destDir, entry.getName());
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        int len;
        while ((len = zipInputStream.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, len);
        }
        fileOutputStream.close();
    }
}

}

but it failed with error

files/temp/1ST_FILE_NAME (No such file or directory)

After searching about it I found the follwoing topic Java OutputStream equivalent to getClass().getClassLoader().getResourceAsStream() where it is stated that In general, you cannot put stuff back into a resource you got from the classloader. But even if you could it is considered a bad practice.

But where should I store my temporary files in that cases?

PS Since I wasn't sure if the directory would be created when I tried to write a file to it, I created it manually. The error hasn't changed.

Kosh
  • 684
  • 1
  • 4
  • 18
  • 2
    have a look on https://mkyong.com/java/how-to-get-the-temporary-file-path-in-java – ShaharT May 09 '22 at 20:47
  • [Creating Temporary Directories in Java](https://www.baeldung.com/java-temp-directories); [How to get the temporary file path in Java](https://mkyong.com/java/how-to-get-the-temporary-file-path-in-java/); [How to create a temporary directory/folder in Java?](https://stackoverflow.com/questions/617414/how-to-create-a-temporary-directory-folder-in-java) – MadProgrammer May 09 '22 at 21:40
  • Also, see [`File#mkdirs`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/io/File.html#mkdirs()) – MadProgrammer May 09 '22 at 21:41

0 Answers0