使用StreamingOutput传输巨大的文件而不会引起heapSpace的愤怒

时间:2019-02-14 10:57:50

标签: java jax-rs

我一直在尝试使用流输出在restapi上传输|传输本地文件系统中可用的巨大文件。我一直遇到heapSpace错误。谁能帮助我找出我做错了什么?据我了解,streamingoutput不应将文件保留在内存中。

请在下面找到代码:

public Response getBulkBillDownload(@QueryParam("requestID") String requestID,
        @QueryParam("zipFileName") String zipFileName) throws RestException {

    StreamingOutput stream = null;
    try {
        File file = null;
        Optional<File> document = getCorporatePaymentManager().getBulkBillDownloadResponse(requestID, zipFileName);
        if (document.isPresent()) {
            file = document.get();
        } else {
            throw new RestException("File not found");
        }

        final FileInputStream fStream = new FileInputStream(file);

        // register stream to Response and it will callback with server OutputStream
        stream = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
               pipe(fStream, output);                    
            }
        };

    } catch (Exception e) {
        handleException(e);
    }

    return Response.status(200).entity(stream).header("Content-Disposition", "attachment; filename=" + zipFileName)
            .build();
}

private void pipe(InputStream is, OutputStream os) throws IOException {

    byte[] buf=new byte[1024];
    int bytesread = 0, bytesBuffered = 0;
    while( (bytesread = is.read( buf )) > -1 ) {
        os.write( buf, 0, bytesread );
        bytesBuffered += bytesread;
        if (bytesBuffered > 1024 * 1024) { //flush after 1MB
            bytesBuffered = 0;
            os.flush();
        }
    }        
    os.close();
}

0 个答案:

没有答案