Download large video file getting corrupted

2019-07-10 04:29发布

In server side code, I have set buffer size and content length as File.length() and then Opened File using FileInputStream. Later fetching output stream using HttpResponse.getOutputStream() and dumping bytes of data that is read using FileInputStream

I am using Apache Tomcat 7.0.52, Java 7


On Client
File Downloader.java

URL url = new URL("myFileURL");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoInput(true);
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.setRequestMethod("GET");
con.setUseCaches(false);
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.connect();
FileOutputStream fos = new FileOutputStream("filename");
if(con.getResponseCode()==200){
    InputStream is = con.getInputStream();
    int readVal;
    while((readVal=is.read())!=-1) fos.write(readVal);
}
fos.flush()
fos.close();

So above code failed to download large file. On client using Java 7

标签: java tomcat
2条回答
做自己的国王
2楼-- · 2019-07-10 04:41
    fos.flush();
} finally {
    fos.close();
    con.close();
} 
查看更多
\"骚年 ilove
3楼-- · 2019-07-10 04:43

Can You try this

 FileOutputStream outputStream = new FileOutputStream(fileName);
 int bytesRead;
 byte[] buffer = new byte[1024];
 while ((bytesRead = inputStream.read(buffer)) != -1) {
     outputStream.write(buffer, 0, bytesRead);
 }

Quoting from https://stackoverflow.com/a/45453874/4121845

Because you only want to write data that you actually read. Consider the case where the input consists of N buffers plus one byte. Without the len parameter you would write (N+1)*1024 bytes instead of N*1024+1 bytes. Consider also the case of reading from a socket, or indeed the general case of reading: the actual contract of InputStream.read() is that it transfers at least one byte, not that it fills the buffer. Often it can't, for one reason or another.

查看更多
登录 后发表回答