简体   繁体   中英

Download Large Files using java

I am building an application in which I want to download large files on handset (mobile), but if size of file is large I am getting exception socket exception-broken pipe.

 resp.setHeader("Content-length", "" + fileLength);  
    resp.setContentType("application/vnd.ms-excel");  
    resp.setHeader("Content-Disposition","attachment; filename=\"export.mpr\"");  
    FileInputStream inputStream = null;  
 try  
 {  
    inputStream = new FileInputStream(path);  
    byte[] buffer = new byte[1024];  
    int bytesRead = 0;  

    do  
    {  
            bytesRead = inputStream.read(buffer, offset, buffer.length);  
            resp.getOutputStream().write(buffer, 0, bytesRead);  
    }  
    while (bytesRead == buffer.length);  

    resp.getOutputStream().flush();  
}  
finally  
{  
    if(inputStream != null)  
            inputStream.close();  
}  

I do not know if this is related to your problem, but it looks like you are not using read() correctly. read() returns -1 upon end of input, and may read less than the specified number of bytes even if more data is available. I would recommend instead using

while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
    resp.getOutputStream().write(buffer, 0, bytesRead);
}

Your original code risks terminating the read loop before end of data, or calling write() with bytesRead set to -1. Also, the offset variable in your original code seems unnecessary; the offset should always be 0, since you are trying to fill the entire buffer.

If you're getting a SocketException, the problem isn't with the code here, but with the underlying networking protocol. In this case, "broken pipe" means that you're losing the connection to the server -- either because the server is hanging up, the Internet connection is shaky, or something else -- and read is throwing the exception because it happens to be the method trying to use that connection at the moment.

使用BufferedInputStream而不是FileInputStream可以为您提供更多的功能和灵活性,以读取数据。

What's your application's environment? I mean which AppServer, WebServer etc.

I had a similar issue when serving large file through Apache Httpd and Tomcat combo. My clients were using a normal webbrowser, and I was trying to send chunked data. (For very large files I was reading a chunk of bytes and sending it out to client).

My problem was probably because of the ajp connecter I was using between httpd and tomcat. I switched from ajp to html connector between the two and it worked like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM