我想用java下载一个HTTP查询,但是我下载的文件在下载时有一个未确定的长度。
我认为这将是相当标准的,所以我搜索并找到了它的代码片段:http://snipplr.com/view/33805/ http://snipplr.com/view/33805/
但它有一个 contentLength 变量的问题。由于长度未知,我得到 -1。这会产生错误。当我省略有关 contentLength 的整个检查时,这意味着我始终必须使用最大缓冲区。
但问题是文件还没有准备好。因此刷新只被部分填充,部分文件会丢失。
如果您尝试下载类似的链接http://overpass-api.de/api/interpreter?data=area%5Bname%3D%22Hoogstade%22%5D%3B%0A%28%0A++node%28area%29%3B%0A++%3C%3B %0A%29+%3B%0Aout+元+qt%3B http://overpass-api.de/api/interpreter?data=area%5Bname%3D%22Hoogstade%22%5D%3B%0A%28%0A++node%28area%29%3B%0A++%3C%3B%0A%29+%3B%0Aout+meta+qt%3B使用该代码片段,您会注意到该错误,并且当您总是下载最大缓冲区以忽略该错误时,您最终会得到一个损坏的 XML 文件。
有没有办法只下载文件的准备部分?我希望这是否可以下载大文件(最多几 GB)。
这应该有效,我测试了它并且它对我有用:
void downloadFromUrl(URL url, String localFilename) throws IOException {
InputStream is = null;
FileOutputStream fos = null;
try {
URLConnection urlConn = url.openConnection();//connect
is = urlConn.getInputStream(); //get connection inputstream
fos = new FileOutputStream(localFilename); //open outputstream to local file
byte[] buffer = new byte[4096]; //declare 4KB buffer
int len;
//while we have availble data, continue downloading and storing to local file
while ((len = is.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
} finally {
try {
if (is != null) {
is.close();
}
} finally {
if (fos != null) {
fos.close();
}
}
}
}
如果您希望它在后台运行,只需在线程中调用它:
Thread download = new Thread(){
public void run(){
URL url= new URL("http://overpass-api.de/api/interpreter?data=area%5Bname%3D%22Hoogstade%22%5D%3B%0A%28%0A++node%28area%29%3B%0A++%3C%3B%0A%29+%3B%0Aout+meta+qt%3B");
String localFilename="mylocalfile"; //needs to be replaced with local file path
downloadFromUrl(url, localFilename);
}
};
download.start();//start the thread
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)