Android(安卓)URL 下载文件
16lz
2022-07-22
首先需要一个线程。 new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(entity.getUrl()); //打开连接 URLConnection conn = url.openConnection(); //打开输入流 InputStream is = conn.getInputStream(); //获得长度 int contentLength = conn.getContentLength(); //创建文件夹 MyDownLoad,在存储卡下 String dirName = context.getExternalFilesDir(null).getPath() + "/MyDownLoad/"; File file = new File(dirName); //不存在创建 if (!file.exists()) { file.mkdir(); } //下载后的文件名 String fileName = dirName + entity.getTitle() +".mp3"; 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); } //完成后关闭流 os.close(); is.close(); Log.e("run", "下载完成了~" + dirName ); } catch (Exception e) { e.printStackTrace(); } } }).start();
更多相关文章
- 浅析Android中的消息机制-解决:Only the original thread that cr
- Android之菜单总结
- Android异步消息机制之Handler
- Android的Handler机制详解3_Looper.looper()不会卡死主线程
- Android使用Retrofit进行网络请求
- [RK3399][Android7.1.1] WifiAp:开机默认打开wifi热点
- Android官方入门文档[1]创建一个Android项目
- android 创建桌面快捷方式 、插件
- AIR Native Extension的使用(Android)一 : 打包ane