`
xidajiancun
  • 浏览: 455812 次
文章分类
社区版块
存档分类
最新评论

Android文件下载使用Http协议

 
阅读更多

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;
		}
	}

	@Override
	protected 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要使用线程访问网络,否则将会出现警告
		@Override
		public 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 {
		@Override
		public void onClick(View arg0) {
			new Thread(downloadRun).start();
		}

	}

	class Btn_download2 implements OnClickListener {
		@Override
		public 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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SQLiteStudy" >

    <Button
        android:id="@+id/btn_download1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载文本" />

    <Button
        android:id="@+id/btn_download2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn_download1"
        android:text="下载其他" />

</RelativeLayout>


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics