gpt4 book ai didi

java - URLConnection inputStream 未被完全读取

转载 作者:行者123 更新时间:2023-11-30 09:23:27 27 4
gpt4 key购买 nike

我编写了以下代码来从服务器下载一些文件,但问题是这段代码没有读取完整的响应(inputStream)。文件大小为 7.5 MB,而我每次都获得 5.5 MB,当然 adobe reader 提示文件已损坏。这是代码

import java.net.URLConnection;
public class Downloader {
URL url;
public Downloader(){
try {

url = new URL("https://d396qusza40orc.cloudfront.net/algs4partI/slides%2F13StacksAndQueues.pdf");
FileOutputStream outStream;
ObjectOutputStream oStream;
try {
URLConnection con = url.openConnection();
InputStream inStream = con.getInputStream();
outStream = new FileOutputStream("data.pdf");
oStream = new ObjectOutputStream(outStream);
int bytesRead;
int totalBytesRead = 0;
byte[] buffer = new byte[100000];
while((bytesRead = inStream.read(buffer)) > 0){

//outStream.write(buffer, 0 , bytesRead);
oStream.write(buffer, 0, bytesRead);
buffer = new byte[100000];
totalBytesRead += bytesRead;
}
System.out.println("Total Bytes read are = " + totalBytesRead);
oStream.close();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static void main(String[] args){
Downloader d = new Downloader();
}

知道我在这里做错了什么吗?提前致谢。

最佳答案

当您不序列化 Java 对象时,您不希望使用 ObjectOutputStream

取消注释行

//outStream.write(buffer, 0 , bytesRead);

并删除

oStream.write(buffer, 0, bytesRead);

所以:

while((bytesRead = inStream.read(buffer)) > 0){

outStream.write(buffer, 0 , bytesRead);
buffer = new byte[100000]; // this line is useless
totalBytesRead += bytesRead;
}

完全摆脱 ObjectOutputStream。您的文件长 5.25 MB(5,511,685 字节),而不是 7.5 MB。

关于java - URLConnection inputStream 未被完全读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16019186/

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