java 如何在 REST 响应后删除文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26930127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:53:50  来源:igfitidea点击:

How to delete file after REST response

javarestresteasy

提问by tarka

What is the best way to handle deleting a file after it has been returned as the response to a REST request?

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

I have an endpoint that creates a file on request and returns it in the response. Once the response has been dispatched the file is no longer needed and can/should be removed.

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

@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!

}

I guess I could create a tmp file but I would have thought there was a more elegant mechanism to achieve this. The file could be quite large so I cannot load it into memory.

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

采纳答案by cmaulini

There is a more elegant solution, don't write a file, just write directly to the output stream contained in the instance of Response.

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

回答by cmaulini

Use a StreamingOutput as entity:

使用 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);
        }
    }
}

回答by sinclair

Without knowing the context of your application, you can delete the file when the VM exits:

在不知道应用程序上下文的情况下,您可以在 VM 退出时删除该文件:

file.deleteOnExit();    

See: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit%28%29

请参阅:https: //docs.oracle.com/javase/7/docs/api/java/io/File.html#deleteOnExit%28%29

回答by Praneeth

I did something like this recently in rest service development using jersey

我最近在使用 jersey 的休息服务开发中做了类似的事情

@GET
@Produces("application/zip")
@Path("/export")
public Response exportRuleSet(@QueryParam("ids") final List<String> ids) {

    try {
        final File exportFile = serviceClass.method(ruleSetIds);

        final InputStream responseStream = new FileInputStream(exportFile);


        StreamingOutput output = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {  
                int length;
                byte[] buffer = new byte[1024];
                while((length = responseStream.read(buffer)) != -1) {
                    out.write(buffer, 0, length);
                }
                out.flush();
                responseStream.close();
               boolean isDeleted = exportFile.delete();
                log.info(exportFile.getCanonicalPath()+":File is deleted:"+ isDeleted);                 
            }   
        };
        return Response.ok(output).header("Content-Disposition", "attachment; filename=rulset-" + exportFile.getName()).build();
    }

回答by silentCode

save the response in a tmp variable with replacing your return statement like this:

将响应保存在 tmp 变量中,并像这样替换 return 语句:

Response res = response.build();
//DELETE your files here.
//maybe this is not the best way, at least it is a way.
return res;

回答by Abdelkader

send file name on response:

响应时发送文件名:

return response.header("filetodelete", FILE_OUT_PUT).build();

after that you can send delete restful method

之后你可以发送删除restful方法

@POST
@Path("delete/{file}")
@Produces(MediaType.TEXT_PLAIN)
public void delete(@PathParam("file") String file) {

    File delete = new File(file);

    delete.delete();

}