java - URLConnection inputStream 未完全读取

标签 java response urlconnection

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

相关文章:

java - 无法在 android 中打开 URLConnection

java - Android Studio 1.4 - 在根项目 'assemble' 中找不到任务 'bin'

java - 我的应用程序在本地服务器上使用 itext 加密 pdf 文件正常,但在 QA 服务器上失败

java - 亚马逊广告 API 导致我的应用崩溃?

javascript - React Native 如何清空数据源

c# - WCF 客户端接收空响应值

android - HTC One 漏洞?出现在 URLConnection InputStream 中的部分 HTTP header

Java正则表达式仅替换html文件中的文本

javascript - 资源响应被削减

java - 带有 Cookie 的 URL 连接?