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.