Android文件下载功能实现代码
本文实例为大家分享了Android文件下载功能的具体代码,供大家参考,具体内容如下
1.普通单线程下载文件:
直接使用URLConnection.openStream()打开网络输入流,然后将流写入到文件中!
publicstaticvoiddownLoad(Stringpath,Contextcontext)throwsException { URLurl=newURL(path); InputStreamis=url.openStream(); //截取最后的文件名 Stringend=path.substring(path.lastIndexOf(".")); //打开手机对应的输出流,输出到文件中 OutputStreamos=context.openFileOutput("Cache_"+System.currentTimeMillis()+end,Context.MODE_PRIVATE); byte[]buffer=newbyte[1024]; intlen=0; //从输入六中读取数据,读到缓冲区中 while((len=is.read(buffer))>0) { os.write(buffer,0,len); } //关闭输入输出流 is.close(); os.close(); }
2.普通多线程下载:
步骤:
- 获取网络连接
- 本地磁盘创建相同大小的空文件
- 计算每条线程需从文件哪个部分开始下载,结束
- 依次创建,启动多条线程来下载网络资源的指定部分
publicclassDownloader{ //添加@Test标记是表示该方法是Junit测试的方法,就可以直接运行该方法了 @Test publicvoiddownload()throwsException { //设置URL的地址和下载后的文件名 Stringfilename="meitu.exe"; Stringpath="http://10.13.20.32:8080/Test/XiuXiu_Green.exe"; URLurl=newURL(path); HttpURLConnectionconn=(HttpURLConnection)url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //获得需要下载的文件的长度(大小) intfilelength=conn.getContentLength(); System.out.println("要下载的文件长度"+filelength); //生成一个大小相同的本地文件 RandomAccessFilefile=newRandomAccessFile(filename,"rwd"); file.setLength(filelength); file.close(); conn.disconnect(); //设置有多少条线程下载 intthreadsize=3; //计算每个线程下载的量 intthreadlength=filelength%3==0?filelength/3:filelength+1; for(inti=0;i以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。