3

I want to do cleanup of files after creating zip file. One of those action is to delete the zip file itself.

    @RequestMapping(path = "/downloadZip", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String fileName) throws IOException {

//Create a zip file and add entries

    Path path = Paths.get(file.getAbsolutePath());
    ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);

//Call a cleanup method
//cleanUp();

}

In the Junit tests, I was able to delete the zip file using static method AfterClass .

Question: How to define a method which gets after the return.

Thanks!

Abhilash Muthuraj
  • 2,008
  • 9
  • 34
  • 48
  • 2
    Use try with resources: https://stackoverflow.com/questions/17650970/am-i-using-the-java-7-try-with-resources-correctly – awesoon Jul 12 '18 at 03:35
  • 1
    Wrap the content of the method in a `try / finally` block and do the cleanup in the `finally` block. Also you shouldn't be reading the whole file into memory, instead directly stream it from the file-system to the client, this will save you a lot of memory. – M. Deinum Jul 12 '18 at 06:35
  • I was able to define the cleanup in the finally block, I will look into the AspectJ as suggested by @Snickers3192 in the future iteration. The reason buffer wont work is, we are editing a lot of files ~ 200 MB, then making alterations like file conversion to PDF, changing filenames. Thanks! – Abhilash Muthuraj Jul 12 '18 at 15:42

1 Answers1

1

Firstly I suggest you have a stateless web-app that doesn't need to write files. Simply use buffers instead. Especially when you say you have to clean-up the file afterwards.

But if you can't get away with that and you still want to do tasks after you return something to the user you have a couple of options. You could use Aspects which are quiet nice so you can have a look at AspectJ. Otherwise you can also look at using Futures in conjunction with the @Async annotation on Controller methods.

You may fine that using resources syntax as suggested in the comments will block your method returning the client's call, and you will have to make sure you handle exceptions, files not being cleaned up when some error occurs. IMO you will have some headaches down the line with this approach, such as your file-system being filled.

Derrops
  • 7,651
  • 5
  • 30
  • 60