gpt4 book ai didi

java - 下载大视频文件损坏

转载 作者:行者123 更新时间:2023-11-28 21:57:37 27 4
gpt4 key购买 nike

在服务器端代码中,我将缓冲区大小和内容长度设置为 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com