2
我有一個控制器,它使用ResponseEntity類返回文件流。 但我不確定資源在完成該方法後是否關閉。Spring - 響應文件流的正確方法是什麼?
@RequestMapping(value = "/VMS-49001/playlist/{listName:.+}")
@ResponseBody
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())
.contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl")).headers(headers)
.body(new InputStreamResource(Files.newInputStream(filePath)));
} else {
String errorMsg = "404 file not found";
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.parseMediaType("text/html"))
.body(errorMsg);
}
}
如果你看到下面的代碼片段,Files.newInputStream(文件路徑)實現了可關閉的,所以使用後應關閉,但我找不到代碼關閉它。 :
return ResponseEntity.ok()
.contentLength(filePath.toFile().length())
.contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"))
.headers(headers)
.body(new InputStreamResource(Files.newInputStream(filePath)));
爲了響應文件流,用這段代碼服務文件是否好?或者有沒有「正確」的方法?