Andrew Sasha
Andrew Sasha

Reputation: 1294

Delete tmp file after response?

My use case:

  1. On user request create tmp file (I don't really need to create real file, but I need to have java.io.File instance)
  2. Process this file
  3. Return file and other meta data as json
  4. Remove tmp file permanently

My code looks like:

@GetMapping(produces = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<MultiValueMap<String, Object>> regeneratePdfTest() throws IOException {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    File tempFile = File.createTempFile("temp-file-name", ".tmp");

    processFile(tempFile);

    parts.add("file", new HttpEntity<>(new FileSystemResource(tempFile)));
    parts.add("meta-data", new HttpEntity<>(someObject));

    return new ResponseEntity<>(parts, HttpStatus.OK);
}

(Is this code the best for this case?)

I aware about File.deleteOnExit(), but documentation said

Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification

In my case, I want delete file immediately after response (file have some private information and I don't want keep them, also safe memory as I don't need this file anymore).

File size can be very large (more than 200MB).

Update 1: If error happen I'd like delete file too.

Upvotes: 6

Views: 4422

Answers (1)

CBD
CBD

Reputation: 57

You can use .delete() method to delete the file after using it. I you want to delete it also if error, you can use a try catch and put the delete method inside the catch too. Don't forget to .close() the streams related to the file before deleting, or it won't let you delete it. Moreover, the delete() method returns a boolean true or false, if the deletion was successful or not, you can use that information to manage logging errors, or other actions.

Upvotes: 0

Related Questions