我无法从网上下载大文件(超过 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 {
}
提前致谢。
最佳答案
您忽略了实际读取的字节数:
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);
}
关于java - 我用 Java 做了一个简单的下载管理器,我的下载管理器可以下载但不能从网上下载大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841893/