HttpURLConnection方式直接下载文件

本文介绍了一个简单的Java方法用于从指定URL下载APK文件并保存到指定路径。该方法包括设置线程优先级、连接超时时间、读取输入流并将数据写入文件等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    protected void downloadAPK(String downloadUrl,String fileSavePath) {
 		File downloadFile = null;
		if (TextUtils.isEmpty(downloadUrl))
			return;
		HttpURLConnection connection = null;
		try {
			Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
			URL url = new URL(downloadUrl);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(60000);
			connection.setDoInput(true);
			InputStream is = connection.getInputStream();
			final File temp = new File(fileSavePath);
			if (temp.exists())
				temp.delete();
			temp.createNewFile();
			temp.setReadable(true, false);
			temp.setWritable(true, false);
			downloadFile = temp;
			Log.d("downloadAPK", "downloadUrl " + downloadUrl + "\n save to " + temp);
			OutputStream os = new FileOutputStream(temp);
			byte[] buf = new byte[8 * 1024];
			int len;
			try {
				while ((len = is.read(buf)) != -1) {
					os.write(buf, 0, len);
				}
				os.flush();
				if (os instanceof FileOutputStream) {
					((FileOutputStream) os).getFD().sync();
				}
			} finally {
				closeSilently(os);
				closeSilently(is);
			}
			Log.d("downloadAPK", "download complete url=" + downloadUrl + ", fileSize= " + temp.length());
//			installPkg(this, temp, pkg);
		} catch (Exception e) {
			Log.w("downloadAPK", e);
			if (downloadFile != null)
				downloadFile.delete();

		} finally {
			if (connection != null)
				connection.disconnect();
		}
	}

	public static final void closeSilently(Object closeable) {
		try {
			if (closeable != null) {
				if (closeable instanceof Closeable) {
					((Closeable) closeable).close();
				} else if (closeable instanceof Socket) {
					((Socket) closeable).close();
				} else if (closeable instanceof ServerSocket) {
					((ServerSocket) closeable).close();
				} else {
					throw new IllegalArgumentException("Unknown object to close");
				}
			}
		} catch (IOException e) {
			// ignore
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值