Delete tmp file after response?

Viewed 3391

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.

0 Answers
Related