我编写了以下代码来从服务器下载一些文件,但问题是该代码没有读取完整的响应(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/