Android 文件下载,在Android开发中很长用到,经常需要在应用程序中下载所需要的文件比如电子书,MP3格式的音乐文件,电影等。我在这里总结了一下,以后要用时可以直接拷贝,
代码分析:
有两个工具类,HttpDownloader.java类中定义两个下载方法,download(String urlstr)下载纯文本文件,downfile(String urlStr,String path,String fileName)下载字节文件类。FileUtils.java类定义了写入sd卡的操作。Download.java类为主线程类,两个按钮,监听下载事件。
注意:
在AndroidManifest.xml中添加网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
在AndroidManifest.xml中加入访问SDCard的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
代码:
main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Android_hello word"
- />
- <Button
- android:id="@+id/buttontxt"
- android:layout_width="300dp"
- android:layout_height="wrap_content"
- android:text="单击下载txt文件"
- />
- <Button
- android:id="@+id/buttonmp3"
- android:layout_width="300dp"
- android:layout_height="wrap_content"
- android:text="单击下载mp3文件"
- />
- </LinearLayout>
Download.java
- package com.example.download;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class Download extends Activity {
- private Button buttontxt;
- private Button buttonmp3;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_download);
- buttontxt = (Button) findViewById(R.id.buttontxt);
- buttontxt.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // TODO Auto-generated method stub
- // TODO Auto-generated method stub
- // 创建一个匿名线程用于下载文件
- new Thread() {
- public void run() {
- HttpDownloader httpDownloader = new HttpDownloader();
- // 调用httpDownloader对象的重载方法download下载txt文件
- String txt = httpDownloader
- .download("http://www.baidu.com/");
- System.out.println(txt);
- }
- }.start();
- }
- });
- buttonmp3 = (Button) findViewById(R.id.buttonmp3);
- // 为buttonmp3添加单击事件监听器
- buttonmp3.setOnClickListener(new OnClickListener() {
- /*
- * (non-Javadoc)
- *
- * @see android.view.View.OnClickListener#onClick(android.view.View)
- */
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- new Thread() {
- public void run() {
- try {
- HttpDownloader httpDownloader = new HttpDownloader();
- // 调用httpDownloader对象的重载方法download下载mp3文件
- int result = httpDownloader
- .downfile(
- "http://sjrjy.apkzz.net/201011/291354164ea84578066309.jpg",
- "Android/", "9.jpg");
- System.out.println(result);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
- });
- }
- }
HttpDownloader.java
- package com.example.download;
- 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.URL;
- public class HttpDownloader {
- private URL url=null;
- public String download(String urlstr){
- StringBuffer stringBuffer=new StringBuffer();
- String line;
- BufferedReader bufferedReader=null;
- try {
- //创建一个URL对象
- url=new URL(urlstr);
- //得到一个HttpURLConnection对象
- HttpURLConnection httpsURLConnection=(HttpURLConnection) url.openConnection();
- // 得到IO流,使用IO流读取数据
- bufferedReader=new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
- while((line=bufferedReader.readLine())!=null){//一行一行的读
- stringBuffer.append(line);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return stringBuffer.toString();
- }
- // 该函数返回整形 -1:代表下载文件出错 ;0:代表下载文件成功; 1:代表文件已经存在
- public int downfile(String urlStr,String path,String fileName){
- InputStream inputstream=null;
- FileUtils fileUtils=new FileUtils();
- if(fileUtils.isExist(path+fileName))
- return 1;
- else
- {
- try {
- inputstream=getFromUrl(urlStr);
- } catch (IOException e) {
- e.printStackTrace();
- }
- File file=fileUtils.writeToSDPATHFromInput(path, fileName, inputstream);
- if(file!=null)
- return 0;
- else
- return -1;
- }
- }
- //根据url字符串得到输入流
- public InputStream getFromUrl(String urlStr) throws IOException
- {
- url=new URL(urlStr);
- HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();
- InputStream input=httpUrlConnection.getInputStream();
- return input;
- }
- }
FileUtils.java
- package com.example.download;
- 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 = null;
- public String getSDPATH() {
- return SDPATH;
- }
- public FileUtils() {
- // 获得当前外部存储设备SD卡的目录
- SDPATH = Environment.getExternalStorageDirectory() + "/";
- }
- // 创建文件
- public File createFile(String fileName) throws IOException {
- File file = new File(SDPATH + fileName);
- file.createNewFile();
- return file;
- }
- // 创建目录
- public File createDir(String fileName) throws IOException {
- File dir = new File(SDPATH + fileName);
- dir.mkdir();
- return dir;
- }
- // 判断文件是否存在
- public boolean isExist(String fileName) {
- File file = new File(SDPATH + fileName);
- return file.exists();
- }
- public File writeToSDPATHFromInput(String path, String fileName,
- InputStream inputstream) {
- File file = null;
- OutputStream outputstream = null;
- try {
- createDir(path);
- file = createFile(path + fileName);
- outputstream = new FileOutputStream(file);
- byte buffer[] = new byte[1024];
- // 将输入流中的内容先输入到buffer中缓存,然后用输出流写到文件中, /*真机测试,这段可能有问题
- /*while ((inputstream.read(buffer)) != -1) {
- outputstream.write(buffer);
- }*/
- //用这段
- int length;
- while((length=(inputstream.read(buffer))) >0){
- outputstream.write(buffer,0,length);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- inputstream.close();
- outputstream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
- }