1

我无法从网上下载大文件(超过 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 {

    }

提前致谢。

4

1 回答 1

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);
}
于 2011-10-20T20:37:15.457 回答