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

时间:2011-10-20 20:32:38

标签: java download-manager

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

 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 {

    }

提前致谢。

1 个答案:

答案 0 :(得分:3)

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

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);
}