下载大视频文件损坏 [英] Download large video file getting corrupted

查看:41
本文介绍了下载大视频文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器端代码中,我将缓冲区大小和内容长度设置为 File.length(),然后使用 FileInputStream 打开文件.稍后使用 HttpResponse.getOutputStream() 获取输出流并转储使用 FileInputStream

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

我使用的是 Apache Tomcat 7.0.52、Java 7

I am using Apache Tomcat 7.0.52, Java 7

在客户端
文件下载器.java

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();

所以上面的代码无法下载大文件.在使用 Java 7 的客户端

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

推荐答案

你可以试试这个吗

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

<小时>

引用自 https://stackoverflow.com/a/45453874/4121845

因为您只想写入您实际读取的数据.考虑输入由 N 个缓冲区加一个字节组成的情况.如果没有 len 参数,您将写入 (N+1)*1024 字节而不是 N*1024+1 字节.还要考虑从套接字读取的情况,或者实际上是读取的一般情况: InputStream.read() 的实际约定是它至少传输一个字节,而不是它填充缓冲区.通常不能,出于某种原因.

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.

这篇关于下载大视频文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆