我用Java做了一个简单的下载管理器,我的下载管理器能够下载却无法从网上下载大文件

发布于 2024-12-11 05:50:14 字数 754 浏览 2 评论 0原文

我无法从网上下载大文件(超过 1 MB 的文件)。但是,我的程序能够从本地主机下载这些大文件。下载大文件还需要做什么吗? 这是代码片段:

 try {

        //connection to the remote object referred to by the URL.
        url = new URL(urlPath);
        // connection to the Server
        conn = (HttpURLConnection) url.openConnection();

        // get the input stream from conn
        in = new BufferedInputStream(conn.getInputStream());

        // save the contents to a file
        raf = new RandomAccessFile("output","rw");


        byte[] buf = new byte[ BUFFER_SIZE ];
        int read;

        while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
    {

            raf.write(buf,0,BUFFER_SIZE);
    }

    } catch ( IOException e ) {

    }
    finally {

    }

提前致谢。

I am not able to download large files from the net ( more than 1 mb file ). However, my program is able to download those large files from the localhost. Is there anything else that i need to do to download large files?
Here is the code snippet:

 try {

        //connection to the remote object referred to by the URL.
        url = new URL(urlPath);
        // connection to the Server
        conn = (HttpURLConnection) url.openConnection();

        // get the input stream from conn
        in = new BufferedInputStream(conn.getInputStream());

        // save the contents to a file
        raf = new RandomAccessFile("output","rw");


        byte[] buf = new byte[ BUFFER_SIZE ];
        int read;

        while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
    {

            raf.write(buf,0,BUFFER_SIZE);
    }

    } catch ( IOException e ) {

    }
    finally {

    }

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猥琐帝 2024-12-18 05:50:14

您忽略了实际读取的字节数:

while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
{
    raf.write(buf,0,BUFFER_SIZE);
}

您的 write 调用总是写入整个缓冲区,即使您没有用 read 填充它调用。你想要:

while ((read = in.read(buf, 0, BUFFER_SIZE)) != -1)
{
    raf.write(buf, 0, read);
}

You're ignoring how many bytes you've actually read:

while( ((read = in.read(buf,0,BUFFER_SIZE)) != -1) )
{
    raf.write(buf,0,BUFFER_SIZE);
}

Your write call always writes the whole buffer, even if you didn't fill it with the read call. You want:

while ((read = in.read(buf, 0, BUFFER_SIZE)) != -1)
{
    raf.write(buf, 0, read);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文