背景
这是@RestController中定义的方法,它从磁盘读取文件然后流回。
@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);
}
问题
我希望在提供请求后删除该文件,但无法找到一个好地方。
我认为应该在inputStream关闭之后(https://github.com/spring-projects/spring-framework/blob/v4.3.9.RELEASE/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java#L117)。由于Inputstream打开文件,因此无法在上述方法中完成。
回答总结谢谢大家的帮助。
接受的答案需要最少的改变并且运作良好。
使用您自己的实现扩展FileInputStream
,然后覆盖close
。关闭输入流后,您的文件也会被删除。
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();
}
}
除了在RESTfull服务中对GET请求执行破坏性操作是不好的事实之外,默认的Java库无法做到这一点。更广泛接受的实现是GET,它流式传输文件,然后进行DELETE调用以删除文件。
但是你可以通过实现自己的InputStream来实现它,请参阅deleting files on closing a InputStream上的Stackoverflow中的早期线程。
假设您在同一个控制器中创建该文件。您可以使用:
try (BufferedWriter out = Files
.newBufferedWriter(newFilePath, Charset.defaultCharset(),
StandardOpenOption.DELETE_ON_CLOSE)) {
InputStream in = new FileInputStream(newFilePath.toFile());
InputStreamResource inputStreamResource = new InputStreamResource(in);
httpHeaders.setContentLength(file.Length());
return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
} catch (Exception e) {
}
由于BufferedWriter将在返回时关闭,该文件将被删除。
基于@phlogratos的答案,您可以尝试这样做。
@GetMapping("/download")
public ResponseEntity<InputStreamResource> download() throws Exception {
... codes ...
InputStreamResource isr = new InputStreamResource(new FileInputStream(file) {
@Override
public void close() throws IOException {
super.close();
boolean isDeleted = file.delete();
logger.info("export:'{}':" + (isDeleted ? "deleted" : "preserved"), filename);
}
});
return new ResponseEntity<>(isr, respHeaders, HttpStatus.OK);
}