首先需要一个线程。
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 URL 下载文件
最新推荐文章于 2025-10-25 20:54:56 发布
本文详细介绍了一种在安卓应用中实现文件下载的方法,通过创建线程并利用URL和URLConnection进行网络请求,下载指定URL的文件(如mp3)。文章展示了如何处理文件下载过程中的流操作,包括打开网络连接、读取数据、写入文件以及异常处理。

138

被折叠的 条评论
为什么被折叠?



