My use case:
- On user request create
tmp
file (I don't really need to create real file, but I need to havejava.io.File
instance) - Process this file
- Return file and other meta data as json
- 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.