Android文件下载

看了mars老师的Android视频,真心不错,文件下载的方法,整理一下。

一、文件下载方法:

1. 使用HTTP协议下载文件

2. 将下载的文件写入SDCARD

二、文件下载的具体步骤:

1.    创建一个HttpURLConnection对象

HttpURLConnection urlConn

= (HttpURLConnection)url.openConnection();

2.    获得一个InputStream对象

urlConn.getInputStream()

3.    访问网络的权限

Androidpermission.INTERNET

 

访问SDCARD

得到当前设备SD卡的目录

Environment.getExternalStorageDirectory()

访问SD卡的权限

Android.permission.WRITE_EXTERNAL_STORAGE

具体代码如下:

布局文件:



    
    
 
FileUtils类:
package utils;

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() {
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}
	public File creatSDFile(String fileName) throws IOException{
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	public File creatSDDir(String dirName) {
		File dir = new File(SDPATH + dirName);
		dir.mkdirs();
		return dir;
	}
	
	public boolean isFileExist(String fileName) {
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	public File write2SDFromInput(String path,String fileName,InputStream input){
		File file = null;
		OutputStream output = null;
		try{
			creatSDDir(path);
			file = creatSDFile(path+fileName);
			output = new FileOutputStream(file);
			byte buffer [] = new byte[4*1024];
			while((input.read(buffer)) != -1){
				output.write(buffer);
			}
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally{
			try{
				output.close();
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		return file;
	}
}

 


 HttpDownLoader类:

 

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;

import javax.net.ssl.HttpsURLConnection;

public class HttpDownLoader {

	private URL url = null;
	public String download(String urlStr){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try{
			url = new URL(urlStr);
			HttpURLConnection urlConn =  (HttpsURLConnection) url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			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();
	}
	
	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();
		} finally {
			try{
				inputStream.close();
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return 0;
	}
	
	public InputStream getInputStreamFromUrl(String urlStr)
	        throws MalformedURLException, IOException{
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		return inputStream;
	}
}


 

DownLoad类:

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

public class DownLoad extends Activity{
	private Button downloadTxtButton;
	private Button downloadMp3Button;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		downloadTxtButton = (Button)findViewById(R.id.downloadText);
		downloadTxtButton.setOnClickListener(new DownloadTxtListener());
		
		downloadMp3Button = (Button)findViewById(R.id.downloadMp3);
		downloadMp3Button.setOnClickListener(new DownloadMp3ButtonListener());
	}

	class DownloadTxtListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			HttpDownLoader httpDownloader = new HttpDownLoader();
			String lrc = httpDownloader.download("http://...");
			System.out.println(lrc);
		}
		
	}
	
	class DownloadMp3ButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			HttpDownLoader httpDownloader = new HttpDownLoader();
			int result = httpDownloader.downFile("http://...", "/voal","a1.mp3");
			System.out.println(result);
		}
		
	}
	
}


 

你可能感兴趣的:(Android)