link link - 2 months ago 20
Java Question

Handle temporary file in try with resources

For my application, I have to write a method that takes an

InputStream
as argument, writes the content to a temporary file, performs some operations and finally deletes the temporary.

This is what I have so far:

public void myMethod(InputStream in, String name) {
//...
Path path = Paths.get("./tmp/benchmarks/" + name + ".zip")

try {
Files.copy(in, path);
//operations...
} catch (IOException e) {
//error handling for copy...
} finally {
try {
Files.delete(path));
} catch (IOException e) {
//error handling for delete...
}
}
//...
}


It does the job, but it also looks really ugly. I was wondering if there was some way to use
try-with-resources
to handle this more gracefully.
Is it possible somehow?

UPDATE: I wrote an on-the-fly solution in ten minutes. It looks like this:

public class TemporaryFileHandler implements AutoCloseable {

private File file;

public TemporaryFileHandler(final InputStream in, final Path path) throws IOException {
Files.copy(in, path);
this.file = new File(path.toString());
}

public File getFile() { return file; }

@Override
public void close() throws IOException {
Files.delete(file.toPath());
}
}


I'm sure it's not the best, but it does the job for now. If anyone has suggestions on how to improve this in any way, suggestions are more than welcome.

Answer

Try-with-resource just calls the close method on classes implementing the interfaces implementing java.lang.AutoCloseable. There's nothing from stopping you from creating a File implementation that implements AutoCloseable and deletes itself when close() is called.

You can also call deleteOnExit() on the file to have the JVM delete it when it exits. This is only appropriate if you're okay with waiting until the JVM is done to delete your temporary file. This probably wouldn't be a good idea for a long running JVM like a Java webapp.