当前位置: 首页 > news >正文

android文件下载!download!

在开始代码之前先看一下工程的架构:

Download.java中放入的是程序的主体,util包中放入的是一些公用的方法,其中FileUtils.java放入的是对文件的一些基本操作,HttpDownloader.java中是对下载的一些基本操作。

第一步:先来看看主程序部分

package mars.download; import mars.util.HttpDownloader; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Download extends Activity implements OnClickListener { /** Called when the activity is first created. */ private Button downloadTxtButton; private Button downloadMp3Button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findView(); } public void findView() { downloadTxtButton = (Button) findViewById(R.id.downloadTxt); downloadTxtButton.setOnClickListener(this); downloadMp3Button = (Button) findViewById(R.id.downloadMp3); downloadMp3Button.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub int viewId = v.getId(); switch (viewId) { /** * 这个方法只可以下载文本文件,它是逐行读取字符窜的。 */ case R.id.downloadTxt: { HttpDownloader httpDownloader = new HttpDownloader(); String lrc = httpDownloader.downStr("http://61.184.100.229/");//这个地方的url可以自己定义 Log.e("@@@@", "downloadTxt: " + lrc); } /** * 这个方法可以下载任何文件。 */ case R.id.downloadMp3: { HttpDownloader httpDownloader = new HttpDownloader(); int result = httpDownloader.downFile( "http://192.168.1.107:8080/voa1500/a1.mp3", "voa/", "a1.mp3");//这个地方的url同样可以自己定义 Log.e("@@@@", "downloadMp3"); } default: break; } } }

第二步:看看对sdcard中文件的基本操作

package mars.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.os.Environment; public class FileUtils { private String SDPATH; public String getSDPATH() { return SDPATH; } public FileUtils() { //得到当前SDCARD存储设备的目录 /SDCARD, Environment.getExternalStorageDirectory()这个方法比较通用 SDPATH = Environment.getExternalStorageDirectory() + "/"; } /** * 在SD卡上创建文件 */ public File creatSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } /** * 在SD卡上创建目录 */ public File creatSDDir(String dirName) { File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } /** * 判断SD卡上的文件夹是否存在 */ public boolean isFileExist(String fileName) { File file = new File(SDPATH + fileName); return file.exists(); } /** * 将一个InputStream里面的数据写入到SD卡中 */ public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try//InputStream里面的数据写入到SD卡中的固定方法 { creatSDDir(path); file = creatSDFile(path + fileName); output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; while ((input.read(buffer)) != -1) { output.write(buffer); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { output.close(); } catch (Exception e) { e.printStackTrace(); } } return file; } }

第三步:对下载的基本操作

package mars.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpDownloader { /** * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 * 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 * 3.得到InputStram * 4.从InputStream当中读取数据 */ private URL url = null; public String downStr(String urlStr)//下载字符流的方法 { /** * String和StringBuffer他们都可以存储和操作字符串,即包含多个字符的字符串数据。 * String类是字符串常量,是不可更改的常量。而StringBuffer是字符串变量,它的对象是可以扩充和修改的。 */ StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null;//BufferedReader类用于从缓冲区中读取内容 try { /** * 因为直接使用InputStream不好用,多以嵌套了BufferedReader,这个是读取字符流的固定格式。 */ url = new URL(urlStr);// 创建一个URL对象 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 创建一个Http连接 buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));// 使用IO流读取数据 while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e) { e.printStackTrace(); } } return sb.toString(); } /** * -1:代表下载文件出错 * 0:代表下载文件成功 * 1:代表文件已经存在 */ public int downFile(String urlStr, String path, String fileName)//下载文件的方法 { InputStream inputStream = null; try { FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(path + fileName)) { return 1; } else { inputStream = getInputStreamFromUrl(urlStr); File resultFile = fileUtils.write2SDFromInput(path, fileName,inputStream); if (resultFile == null) { return -1; } } } catch (Exception e) { e.printStackTrace(); return -1; } finally { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } return 0; } /** * 根据URL得到输入流 */ public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { url = new URL(urlStr);// 创建一个URL对象 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 创建一个Http连接 InputStream inputStream = urlConn.getInputStream();//得到输入流 return inputStream; } }

ok!

转载于:https://www.cnblogs.com/boyupeng/archive/2011/03/28/2028538.html

相关文章:

  • SQL Server 2008 表变量参数(表值参数)用法
  • Java类加载器加载类顺序
  • UML类图小结
  • 系统动力学软件vensim之指数增长
  • 系统动力学软件vensim学习之一阶负反馈
  • 数字水印学习教程
  • Nature Science 2010-2011年全部期刊下载链接
  • QTE安装汉化添加新程序全过程
  • 努力我可以
  • linux 与 虚拟机共享数据
  • GNU make指南
  • Linux扩展swap分区大小
  • 实现了回写功能---报表工具功能之一
  • 分析两种实现多线程的方式:Thread类和Runnable接口
  • 直接来我的私人博客吧
  • [ JavaScript ] 数据结构与算法 —— 链表
  • [笔记] php常见简单功能及函数
  • 【跃迁之路】【669天】程序员高效学习方法论探索系列(实验阶段426-2018.12.13)...
  • DataBase in Android
  • Java到底能干嘛?
  • JS笔记四:作用域、变量(函数)提升
  • Mysql5.6主从复制
  • quasar-framework cnodejs社区
  • React-flux杂记
  • 多线程事务回滚
  • 十年未变!安全,谁之责?(下)
  • 收藏好这篇,别再只说“数据劫持”了
  • 智能网联汽车信息安全
  • 湖北分布式智能数据采集方法有哪些?
  • #[Composer学习笔记]Part1:安装composer并通过composer创建一个项目
  • #LLM入门|Prompt#3.3_存储_Memory
  • #stm32整理(一)flash读写
  • (java)关于Thread的挂起和恢复
  • (二)linux使用docker容器运行mysql
  • (二)WCF的Binding模型
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (篇九)MySQL常用内置函数
  • (四)【Jmeter】 JMeter的界面布局与组件概述
  • (转)http-server应用
  • (转)用.Net的File控件上传文件的解决方案
  • .bat批处理(九):替换带有等号=的字符串的子串
  • .NET 2.0中新增的一些TryGet,TryParse等方法
  • .NET中统一的存储过程调用方法(收藏)
  • @configuration注解_2w字长文给你讲透了配置类为什么要添加 @Configuration注解
  • @private @protected @public
  • @拔赤:Web前端开发十日谈
  • [ vulhub漏洞复现篇 ] Django SQL注入漏洞复现 CVE-2021-35042
  • [AIGC] Redis基础命令集详细介绍
  • [C# 开发技巧]如何使不符合要求的元素等于离它最近的一个元素
  • [C++] 多线程编程-thread::yield()-sleep_for()
  • [CDOJ 838]母仪天下 【线段树手速练习 15分钟内敲完算合格】
  • [Django 0-1] Core.Email 模块
  • [HackMyVM]靶场Crossbow
  • [Hadoop in China 2011] Hadoop之上 中国移动“大云”系统解析
  • [hdu1561] The more, The Better 【树形DP】