JustinB JustinB - 2 years ago 165
Java Question

Spring - What is right way to response file stream?

I have a controller which returns file stream using ResponseEntity class.
But I'm not sure if the resource is closed after finished the method.

@RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
public ResponseEntity<?> playlist(HttpServletRequest request, HttpServletResponse response,
@PathVariable String listName) throws IOException {

String hlsPath = getHLSPath(request.getParameter("dt"), listName, OtuEnum.URLType.HLS);
Path filePath = Paths.get(hlsPath);

if (filePath.toFile().exists()) {
Path fileNamePath = filePath.getFileName();
String fileName = "";
if (fileNamePath != null) {
fileName = fileNamePath.toString();
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData(fileName, fileName);

return ResponseEntity.ok().contentLength(filePath.toFile().length())
.body(new InputStreamResource(Files.newInputStream(filePath)));
} else {
String errorMsg = "404 file not found";
return ResponseEntity.status(HttpStatus.NOT_FOUND)

if you see below code fragment, Files.newInputStream(filePath) implements Closeable, so it should be closed after use but I can't find the code closing it. :

return ResponseEntity.ok()
.body(new InputStreamResource(Files.newInputStream(filePath)));

To response file stream, is it good to serve the file with this code? Or is there any "right" approach?

Answer Source

With Spring 4.1 your approach will work there is no issue in it. Here below is another approach in case if you want to look :

@RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
public ResponseEntity<byte[]> testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");

    final HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData(fileName, fileName);

    return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download