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