【Android根据URL下载文件保存到SD卡】莫问天涯路几重,轻衫侧帽且从容。这篇文章主要讲述Android根据URL下载文件保存到SD卡相关的知识,希望能为你提供帮助。
- //下载具体操作
- private void download() {
- try {
- URL url = new URL(downloadUrl);
- //打开连接
- URLConnection conn = url.openConnection();
- //打开输入流
- InputStream is = conn.getInputStream();
- //获得长度
- int contentLength = conn.getContentLength();
- Log.e(TAG, "contentLength = " + contentLength);
- //创建文件夹 MyDownLoad,在存储卡下
- String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";
- File file = new File(dirName);
- //不存在创建
- if (!file.exists()) {
- file.mkdir();
- }
- //下载后的文件名
- String fileName = dirName + "xiaomibianqian.apk";
- File file1 = new File(fileName);
- if (file1.exists()) {
- file1.delete();
- }
- //创建字节流
- byte[] bs = new byte[1024];
- int len;
- OutputStream os = new FileOutputStream(fileName);
- //写数据
- while ((len = is.read(bs)) != -1) {
- os.write(bs, 0, len);
- }
- //完成后关闭流
- Log.e(TAG, "download-finish");
- os.close();
- is.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- String dirName = Environment.getExternalStorageDirectory() + "/MyDownLoad/";
-
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> < uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
推荐阅读
- Android studio导入项目时的问题(Re-download dependencies and sync project (requires network))
- Android中Activity被系统会收前页面信息保存
- Android资源文件命名与使用
- Codeforces Round #468 (Div. 2, based on Technocup 2018 Final Round)D. Peculiar apple-tree
- Android Studio怎样创建App项目
- Android手机的USB转串口开发硬件以及软件源代码
- 手机蓝牙转串口硬件和ANDROID的APK程序开发源代码
- adb获取App的包名和启动页
- 御安全浅析安卓开发代码混淆技术