java - 下载大型视频文件被损坏

标签 java tomcat

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

我正在使用 Apache Tomcat 7.0.52、Java 7


在客户端
文件下载器.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 的客户端上

最佳答案

你能试试这个吗

 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

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.

关于java - 下载大型视频文件被损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50700146/

相关文章:

java - 哪里可以找到 OpenJDK 1.6.0_24 的增量版本?

java - 使用 JDom 格式化 XML,每行一个属性

java - 无法在外部 tomcat 中部署 spring boot 应用程序

java - Spring AOP 中的 NamedParameterJdbcTemplate 和 CGlib

java - 为什么 Tomcat 7 内存使用情况看起来像锯? (图片)

java - 使用 if 条件检查和 ReplaceAll 进行代码优化

javascript - 在 tomcat 服务器(本地主机)上运行时未显示 amcharts

debugging - 使用 Tomcat Maven 插件在 IntelliJ IDEA 中调试 JSP

java - 在 RESTLet DAO Client Server Architecture In Java 中配置回退数据源

java - Jython 和独立数据库连接池 : How to confirm the pool is a Singleton