阅读更多

Android文件下载做法和JAVA的网络编程差不多,我没有使用第三方插件、方法。做的比较粗糙,高手绕道哈。

JAVA code

 

package cn.qiuzhping.study;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class DownloadStudy extends Activity {private Button btn_download1 = null;private Button btn_download2 = null;/** * @项目名称:study * @类名称:HttpDownloder * @作者:Qiuzhping * @时间:2013-12-29下午11:04:11 * @作用 :根据Http协议下载文件 */public class HttpDownloader {private URL url = null;/** * @方法名: download * @作者:Qiuzhping * @作用: 根据网络路径 下载文本文件 * @返回值类型: String */public String download(String urlStr) {StringBuffer sb = new StringBuffer();String line = null;BufferedReader bufferReader = null;try {url = new URL(urlStr);HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));// BufferedReader// 从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取while ((line = bufferReader.readLine()) != null) {// 按行读取文本sb.append(line);}} catch (Exception e) {e.printStackTrace();Log.w("download", "文本文件下载异常!!!");} finally {try {if (bufferReader != null)bufferReader.close();} catch (IOException e) {e.printStackTrace();Log.w("download", "bufferReader关闭异常!!!");}}return sb.toString();}/** * @方法名: download * @作者:Qiuzhping * @作用: 下载非文本文件 * @返回值类型: int -1:下载失败 0: 下载成功 1:文件存在 */public int download(String urlStr, String parentName, String fileName) {InputStream in = null;FileUtil fileUtil = new FileUtil();if (fileUtil.isFileExist(parentName + fileName))// 文件已经存在return 1;else {in = getInputStreamFromUrl(urlStr);File file = fileUtil.write2fromIn(parentName, fileName, in);try {if (in != null)in.close();} catch (IOException e) {e.printStackTrace();Log.i("download", "输入流in关闭异常!!!!");}if (file == null)return -1;}return 0;}/** * @方法名: getInputStreamFromUrl * @作者:Qiuzhping * @作用: 获取网络输入流 * @返回值类型: InputStream */public InputStream getInputStreamFromUrl(String urlStr) {InputStream in = null;try {url = new URL(urlStr);HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();in = urlConn.getInputStream();} catch (MalformedURLException e) {e.printStackTrace();Log.w("getInputStreamFromUrl", "初始化url失败!!");} catch (IOException e) {e.printStackTrace();Log.w("getInputStreamFromUrl", "openConnection失败!!");}return in;}}/** * @项目名称:study * @类名称:FileUtil * @作者:Qiuzhping * @时间:2013-12-30上午10:57:12 * @作用 :创建外部存储文件路径为/PATH/packageName/fileName */public class FileUtil {private final String cmd = "cat /proc/mounts";private final String format = "sdcard";private final String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();private String PATH = null;public String getExternlSD() {File file = Environment.getExternalStorageDirectory();File[] files = file.getParentFile().listFiles();for (int i = 0; i < files.length; i++) {Log.i("getExternlSD", files[i].getPath());}return null;}/** * @方法名: getExternalPath * @作者:Qiuzhping * @作用: 获取真正的External sdcard路径 * @返回值类型: String */public String getExternalPath() {BufferedReader read = null;String external_SDCard = sdCard;Runtime runtime = Runtime.getRuntime();try {Process process = runtime.exec(cmd);read = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = read.readLine()) != null) {if (line.toLowerCase().contains(format)) {String[] array = line.split(" ");if (array != null && array.length >= 5) {String temp = array[1].replace("/.android_secure","");if (!sdCard.equals(temp)) {external_SDCard = temp;}}}}} catch (Exception e) {external_SDCard = sdCard;e.printStackTrace();}return external_SDCard;}/** * @方法名: getPath * @作者:Qiuzhping * @作用: 获取包名 * @返回值类型: String */public String getPath() {return PATH;}/** * 默认是在SD卡上创建文件 */public FileUtil() {/* * if (Environment.getExternalStorageState().equals( * Environment.MEDIA_MOUNTED)) { // 得到当前外部存储器的PATH 就是SDCard Path * PATH = Environment.getExternalStorageState() + "/" * +this.getClass().getPackage().getName() + "/"; } */Log.i("FileUtil", this.getClass().getPackage().getName());PATH = getExternalPath();// PATH += this.getClass().getPackage().getName() + "/";getExternlSD();}/** * @方法名: createFile * @作者:Qiuzhping * @作用: 创建文件 * @返回值类型: File */public File createFile(String parentName, String fileName) {String packName = this.getClass().getName();File dir = createDirFile(packName + "/" + parentName);File file = new File(dir.getPath() + "/" + fileName);try {file.createNewFile();} catch (IOException e) {e.printStackTrace();Log.w("createFile", file.getPath() + "创建异常!!!");}Log.w("createFile", file.getPath() + "创建成功!!!");return file;}/** * @方法名: createDirFile * @作者:Qiuzhping * @作用: 创建目录 * @返回值类型: File */public File createDirFile(String dir) {File dirFile = new File(PATH + "/" + dir);dirFile.mkdirs();// 路径长使用mkdirs();Log.i("createDirFile", dirFile.getPath() + "创建成功!!!");return dirFile;}/** * @方法名: isFileExist * @作者:Qiuzhping * @作用: 判断文件是否存在 * @返回值类型: boolean 如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE */public boolean isFileExist(String fileName) {File dirFile = new File(PATH + "/" + fileName);return dirFile.exists();}/** * @方法名: write2fromIuput * @作者:Qiuzhping * @作用: 根据提供的上一级目录parentName和fileName文件名字、二进制输入流in创建文件 * @返回值类型: File */public File write2fromIn(String parentName, String fileName,InputStream in) {File file = null;OutputStream out = null;try {file = createFile(parentName, fileName);// 创建文件out = new FileOutputStream(file);byte[] buffer = new byte[4 * 1024];// 每次缓存4个字节while ((in.read(buffer)) != -1) {out.write(buffer);}out.flush();// 刷新输出流} catch (Exception e) {e.printStackTrace();Log.w("write2fromIuput", "文件创建异常!!");} finally {try {if (out != null)out.close();} catch (IOException e) {e.printStackTrace();Log.w("write2fromIuput", "关闭输出流异常!!!");}}return file;}}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.download_study);btn_download1 = (Button) findViewById(R.id.btn_download1);btn_download1.setOnClickListener(new Btn_download1());btn_download2 = (Button) findViewById(R.id.btn_download2);btn_download2.setOnClickListener(new Btn_download2());}Runnable downloadRun = new Runnable() {//Android 4.0要使用线程访问网络,否则将会出现警告@Overridepublic void run() {HttpDownloader downloader = new HttpDownloader();Log.i("Btn_download1",downloader.download("http://10.0.0.91:8080/ems/down.txt"));Log.i("Btn_download1","状态 = "+ downloader.download("http://10.0.0.91:8080/ems/antlr-2.7.6.jar","jsp", "antlr-2.7.6.jar"));}};class Btn_download1 implements OnClickListener {@Overridepublic void onClick(View arg0) {new Thread(downloadRun).start();}}class Btn_download2 implements OnClickListener {@Overridepublic void onClick(View arg0) {new Thread(downloadRun).start();// HttpDownloader downloader = new HttpDownloader();// Log.i("Btn_download1",// "状态 = "// + downloader.download(// "http://10.0.0.91:8080/ems/index.jsp",// "jsp", "index.jsp"));}}}


xml

 

    



更多相关文章

  1. ReactNative 命令生成bundle文件
  2. Android 手机存储文件各种路径
  3. 修改android studio 默认的so文件检索路径
  4. Android环境变量作用--命令行操作
  5. CreateProcess error=2, 系统找不到指定的文件。
  6. 【Android】Android Layout Binder——根据layout布局文件自动生
  7. android:向手机卡上写入文件时总是不成功,解决办法
  8. 在android中使用HttpURLConnection进行文件上传
  9. 转:Android文件操作总结

随机推荐

  1. MySQL如何选择合适的索引
  2. mysql类似oracle rownum写法实例详解
  3. mysql如何比对两个数据库表结构的方法
  4. MySQL查看数据库表容量大小的方法示例
  5. sql 流水号获取代码实例
  6. MySQL修改root密码的4种方法(小结)
  7. Windows10下安装解压版MySQL教程图文详解
  8. MySQL 触发器定义与用法简单实例
  9. 往MySQL中存储图片的方法
  10. 利用MySQL系统数据库做性能负载诊断的方