Android开发之下载文件

    Android开发中,文件下载时必须的,在此总结一下。

    Android文件下载需要的准备工作:1、联网和读写SD卡的权限设置;2、HttpURLConnection的使用知识;3、流式操作读写文件的知识。

    以下是我自己写的示例代码,用以理解Android文件下载。

    

1、AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloader"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloader.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    <uses-permission android:name="android.permission.INTERNET"/>      
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

</manifest>

2、activity_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="你好"
    />
<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>


3、MainActivity.java


package com.example.downloader;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button buttontxt;
	private Button buttonmp3;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttontxt=(Button)findViewById(R.id.buttontxt);
        //为buttontxt添加单击事件监听器
        buttontxt.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()
					{
						HttpDownloader httpDownloader=new HttpDownloader();	
						//调用httpDownloader对象的重载方法download下载txt文件
						String txt=httpDownloader.download("http://192.168.1.84:8080/Android/1.txt");				
						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.download("http://192.168.1.84:8080/Android/1.mp3","Android/","music.mp3");
							System.out.println(result);
							}
							catch(Exception e)
							{
								e.printStackTrace();
							}	
						}
				}.start();
				
			}
        });
    }
}


4、HttpDownloader.java


package com.example.downloader;

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 bufferReader=null;
		try
		{
			//创建一个URL对象
			url=new URL(urlStr);			
			//得到一个HttpURLConnection对象
			HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();	
			// 得到IO流,使用IO流读取数据
			bufferReader=new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
			while((line=bufferReader.readLine())!=null)
			{				
				stringbuffer.append(line);
			}			
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}				
		return stringbuffer.toString();
		
	}
	// 该函数返回整形 -1:代表下载文件出错 ;0:代表下载文件成功; 1:代表文件已经存在
    public int download(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) {
				// TODO Auto-generated catch block
				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;
    }
}

5、FileUtils.java


package com.example.downloader;

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[128];
			// 将输入流中的内容先输入到buffer中缓存,然后用输出流写到文件中
			do {
				int length = (inputstream.read(buffer));
				if (length != -1) {
					outputstream.write(buffer, 0, length);
				} else {
					break;
				}
			} while (true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				outputstream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return file;
	}
}

注意:AndroidMainfest.xml中声明了联网权限和读写文件权限;activity_main.xml中布局了两个按钮,分别绑定下载txt文件盒下载mp3文件的事件;HttpDownloader.java里面封装了从网络地址获取流的方法;FileUtils.java实现从流将数据写入文件。写文件的时候,随时注意buffer大小,否则会导致文件为空或者写失败。



Android开发之下载文件,布布扣,bubuko.com

Android开发之下载文件

上一篇:【android学习】安卓设备实现触摸事件的监听,跨进程事件注入


下一篇:在ASP.NET程序中用程序动态向便签里添加标签