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



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

 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 {
    }

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

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

相关内容

  • 没有找到相关文章

最新更新