java 设置下载文件大小_使用Java通过HTTP未知长度下载文件

该博客介绍了一个Java方法,用于从URL下载文件,即使文件的大小在连接时未知。通过使用`URLConnection`打开连接并读取输入流,将数据写入本地文件。示例代码在一个线程中运行,允许在后台下载文件。
摘要由CSDN通过智能技术生成

这应该工作,我测试它,它适用于我:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值