REST响应后如何删除文件

tar*_*rka 18 java rest resteasy

在将文件作为对REST请求的响应返回后,处理删除文件的最佳方法是什么?

我有一个端点,根据请求创建一个文件并在响应中返回它.一旦调度响应,就不再需要该文件,可以/应该删除该文件.

@Path("file")
@GET
@Produces({MediaType.APPLICATION_OCTET_STREAM})
@Override
public Response getFile() {

        // Create the file
        ...

        // Get the file as a steam for the entity
        File file = new File("the_new_file");

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition", "attachment; filename=\"the_new_file\"");
        return response.build();

        // Obviously I can't do this but at this point I need to delete the file!

}
Run Code Online (Sandbox Code Playgroud)

我想我可以创建一个tmp文件,但我认为有一个更优雅的机制来实现这一目标.该文件可能非常大,因此我无法将其加载到内存中.

cma*_*ini 12

使用StreamingOutput作为实体:

final Path path;
...
return Response.ok().entity(new StreamingOutput() {
    @Override
    public void write(final OutputStream output) throws IOException, WebApplicationException {
        try {
            Files.copy(path, output);
        } finally {
            Files.delete(path);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这工作完美,应该被接受的答案,因为提供一个工作示例! (2认同)

小智 9

有一个更优雅的解决方案,不写文件,只是直接写入实例中包含的输出流Response.

  • 您能否提供有关直接写入输出流的详细信息? (5认同)