1

I'm sending a file using the response << file.newInputStream (similar to this answer here, but I want to delete this file afterwards. However, when I call delete on this file, it doesn't delete it. I'm quite sure it's because the file is still in use (streaming). How an I check this and then delete.

    def tempfile = new File(filename)
    if (tempfile) {
       response.setContentType("application/octet-stream")
       response.setHeader("Content-disposition", "attachment;filename=${tempfile.getName()}")
       response.outputStream << tempfile.newInputStream()
    } else {
       renderErrorMsg("ERROR: Cannot open/find file - ${filename}.")
    }
    tempfile.delete()

Thanks.

Community
  • 1
  • 1
ibaralf
  • 12,218
  • 5
  • 47
  • 69

1 Answers1

3

You're not closing the input stream. Change

response.outputStream << tempfile.newInputStream()

To

tempfile.withInputStream { response.outputStream << it }

The latter will ensure the stream is closed. Also you may want to delete the file in a finally block in case an exception is thrown.

Graeme Rocher
  • 7,985
  • 2
  • 26
  • 37
  • Thanks! I did have it in a try-catch but want to simplify the sample code. Do you have a link where this is explained in more detail? – ibaralf Feb 13 '12 at 18:32