tarka tarka - 1 month ago 12x
Java Question

How to delete file after REST response

What is the best way to handle deleting a file after it has been returned as the response to a REST request?

I have an endpoint that creates a file on request and returns it in the response. Once the response has been dispatched the file is no longer needed and can/should be removed.

public Response getFile() {

// Create the file

// Get the file as a steam for the entity
File file = new File("the_new_file");

ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=\"the_new_file\"");
return response.build();

// Obviously I can't do this but at this point I need to delete the file!


I guess I could create a tmp file but I would have thought there was a more elegant mechanism to achieve this. The file could be quite large so I cannot load it into memory.


There is a more elegant solution, don't write a file, just write directly to the output stream contained in the instance of Response.