Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 375
link Avatar asked Dec 02 '15 17:12

link


People also ask

How do I pull up a temporary file?

Find where your temp files are stored by pressing and holding the Windows button, and then hit R to bring up the Run dialogue box. Type temp and press Enter (or click OK) to open up the folder location and see your temp files.

What does Tempfile mean in Python?

Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done.

What does Tempfile Mkdtemp return?

The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it. The prefix, suffix, and dir arguments are the same as for mkstemp() . mkdtemp() returns the absolute pathname of the new directory.

What is a temporary file example?

For example, Microsoft Windows and Windows programs often create a file with a . tmp file extension as a temporary file. Programs like Microsoft Word may create a temporary hidden file beginning with a tilde and a dollar sign (e.g., ~$example. doc) in the same directory as the document.


2 Answers

I think with a little helper / wrapper like

public class AutoDeletingTempFile implements AutoCloseable {

    private final Path file;

    public AutoDeletingTempFile() throws IOException {
        file = Files.createTempFile(null, null);
    }

    public Path getFile() {
        return file;
    }

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

which gets closed and deletes the file it wraps you get a nice and short syntax:

public void myMethod(InputStream in, String name) {
    try (AutoDeletingTempFile wrapper = new AutoDeletingTempFile()) {
        //Files.copy(in, wrapper.getFile());
        //operations...
    } catch (IOException e) {
        //error handling for copy...
        // + temp file creation
    }
}

or a neat little Closable via lambdas

public void myMethod(InputStream in, Path existingFile, String name) {
    try (Closeable closable = () -> Files.deleteIfExists(existingFile)) {
        // ...
    } catch (IOException e) {
        // 
    }
}
like image 80
zapl Avatar answered Sep 20 '22 04:09

zapl


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.

like image 20
Jazzepi Avatar answered Sep 21 '22 04:09

Jazzepi