Search code examples
javaspringspring-restcontroller

Spring @RestController - after request being served


Background

here is the method defined in @RestController, it reads file from disk then stream back.

@RequestMapping(value = "/bill", method = RequestMethod.GET)
public ResponseEntity<Object> getbill(){
  ...
  InputStream in = new FileInputStream(file);
  InputStreamResource inputStreamResource = new InputStreamResource(in);
  httpHeaders.setContentLength(file.Length());
  return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
}

Issue

I would like to delete the file after request is served, but unable to find a good place.

I would assume it should be after inputStream gets closed (https://github.com/spring-projects/spring-framework/blob/v4.3.9.RELEASE/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java#L117) . it can not be done in above method since file is opened by Inputstream.

Answer Summary Thank you all for helping with this.

The accepted answer requires least change and working well.


Solution

  • Extend FileInputStream with your own implementation and then overwrite close. When the input stream is closed, your file gets deleted as well.

    public class MyFileInputStream extends FileInputStream {
        private final File myFile;
    
        public MyFileInputStream(File file) throws FileNotFoundException {
            super(file);
            myFile = file;
        }
        @Override
        public void close() throws IOException {
            super.close();
            myFile.delete();
        }
    }