现在的位置: 首页 > 综合 > 正文

android文件下载!download!

2013年02月19日 ⁄ 综合 ⁄ 共 4583字 ⁄ 字号 评论关闭

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

抱歉!评论已关闭.