Android学习第17课—文件下载

主要内容:
1 使用HTTP协议下载文件

2 将下载的文件写入SDCARD

文件下载步骤

*创建一个HttpURLConnection对象HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();

*获得一个InputStream对象urlConn.getInputStream()

* 访问网络的权限android.permission.INTERNET


访问SDCARD步骤:
得到外部存储设备的目录:Environment.getExternalStorageDirectory();

访问SD卡的权限:android:permission.WRITE_EXTERNAL_STORAGE;


package dj.download;

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

public class DownloadActivity extends Activity {
    /** Called when the activity is first created. */
	private Button textButton = null;
	private Button mp3Button = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        textButton.findViewById(R.id.textButton);
        mp3Button.findViewById(R.id.mp3Button);
        textButton.setOnClickListener(new DownloadTextListener());
        mp3Button.setOnClickListener(new DownloadMp3Listener());
        
    }
    
    class DownloadTextListener implements OnClickListener
    {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			HttpDownloader httpDownload = new HttpDownloader();
			String urlStr = httpDownload.Download("www.google.com.hk");
			System.out.println(urlStr);
		}
    	
    }
    
    class DownloadMp3Listener implements OnClickListener
    {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			HttpDownloader httpDownload = new HttpDownloader();
			int result = httpDownload.Download("http://g.top100.cn/16667639/html/player.html?id=S258811a167b239fc&type=song&autoplay=true#loaded", "music", "mp3");
			System.out.println(result);
		}
    	
    }
}

package dj.download;

import java.io.*;
import java.net.*;

public class HttpDownloader {
	private URL url = null;
	
	/**
	 * 这个函数成功下载的前提是,下载的东西必须是文本文件,返回值是文档中的内容
	 * 1 创建一个URL对象
	 * 2 通过URL对象创建HttpURLConnection对象
	 * 3 InputStream
	 * 4 通过InputStream得到数据
	 * @param urlStr
	 * @return
	 */
	public String Download(String urlStr)
	{
		StringBuffer sb= new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		
		try {
			//创建一个URL对象
			url = new URL(urlStr);
			//创建一个http连接
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			//使用IO流读取数据
			buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			while((line = buffer.readLine()) != null)
			{
				sb.append(line);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			try {
				buffer.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		return sb.toString();
		
	}
	
	//下载任意形式的文件,函数的返回值: -1 文件下载错误; 0代表文件下载成功;1代表文件已经存在
	//参数代表的意思:urlStr代表下载路径,path表示存放的位置,fileName表示存放的文件名
	public int Download(String urlStr, String path, String fileName)
	{
		InputStream inputStream = null;
		try {
			FileUtile  fileUtile = new FileUtile();
			
			if(fileUtile.isFileExist(path + fileName))
			{
				return 1;
			}
			else{
				inputStream = getInputStreamFormURL(urlStr);
				File resultFile = fileUtile.writeDataToSD(path, fileName, inputStream);
				if(resultFile == null)
				{
					return -1;
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		finally{
			try {
				inputStream.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}
		
		return 0;
		
	}
	
	//根据URL得到一个输入流
	public InputStream getInputStreamFormURL(String urlStr) throws MalformedURLException, IOException
	{
		url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
		InputStream input = urlConn.getInputStream();
		return input;
	}

}

package dj.download;

import java.io.File;
import java.io.*;

import android.os.Environment;

public class FileUtile 
{
	private String SDPATH;
	
	public FileUtile()
	{
		//得到外部存储设备的目录
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}
	
	//在SD卡上创建文件
	public File createSDFile(String fileName) throws IOException
	{
		File file = new File(SDPATH + fileName); 
		file.createNewFile();
		return file;
		
	}
	
	//在SD卡上创建目录
	public File createSDDiv(String divName)
	{
		File div = new File(SDPATH + divName);
		div.mkdir();
		return div;
	}
	
	//判断SD卡上文件是否存在
	public boolean isFileExist(String fileName)
	{
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	//将InputStream里面的数据写到SD卡中
	public File writeDataToSD(String path, String fileName, InputStream input)
	{
		File file = null;
		OutputStream output = null;
		try {
			createSDDiv(path);//创建目录
			file = createSDFile(fileName);//创建文件
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4 * 1024];
			while(input.read(buffer) != -1)
			{
				output.write(buffer);
			}
			output.flush();
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			try {
				output.close();
			} catch (Exception e2) {
				// TODO: handle exception
				e2.printStackTrace();
			}
		}		
		return file;
	}
	
	
}

(还不是很懂,再找点资料研究一下吧 难过 生气

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值