您的位置:首页 > 移动开发 > Android开发

Android 学习 笔记_05. 文件下载

2013-02-27 14:26 495 查看
文件下载的步骤:

1、创建一个HttpURLConnection对象

HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();

2、获得一个InputStream()对象

urlConn.getInputStream();

3、访问网路的权限

android.permission.INTERNET

现做一个小程序如下,能够下载文本文件和Mp3文件



main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Download_Activity" >

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadText"
android:text="@string/downloadTextButton"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadMp3"
android:text="@string/downloadMp3Button"/>
</LinearLayout>


Download_Activity.java

package zzl.download;

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

public class Download_Activity extends Activity {

private Button downloadMp3Button;
private Button downloadTextButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadMp3Button=(Button)findViewById(R.id.downloadMp3);
downloadTextButton=(Button)findViewById(R.id.downloadText);
downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
downloadTextButton.setOnClickListener(new DownloadTextListener());
}
class DownloadTextListener implements OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownload httpDownloader=new HttpDownload();
String lrc =httpDownloader.download("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5");
System.out.println(lrc);
}
}
class DownloadMp3Listener implements OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownload httpDownloader=new HttpDownload();
int result =httpDownloader.downloadFile("http://photo.weibo.com/152611965/wbphotos/large/photo_id/3549709337146075?refer=weibofeedv5","photo_id/","3549709337146075?refer=weibofeedv5");
System.out.println(result);
}
}

}


HttpDownload.java

package zzl.utils;

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;

/*前提:首先判断所下载的文件是否为纯文本文件
* 1.创建一个URL对象
* 2.通过URL对象获取HttpOpenConnection对象(代表和网络上的http对象的连接)
* 3.获取InputStream对象
* 4.读取数据
* 5.将读取的数据写入SD卡
* */
public class HttpDownload {
private URL url = null;

//下载任何形式 的文本文件
public String download(String urlStr){
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader bufr = null;

try {
// 创建一个URL对象:调用URL函数,将地址传入
url = new URL(urlStr);
//通过URL创建一个HTTP连接
HttpURLConnection con =  (HttpURLConnection)url.openConnection();
//使用IO流读取数据,这里使用到了转换流,提高读取效率  【【 字节流转换成字符流再转换成读取行数据】】
bufr = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = bufr.readLine())!=null){
sb.append(line);
}

} catch (Exception e) {
System.out.println("文本文件下载失败!");
e.printStackTrace();
}finally{
if(bufr!=null)
try {
bufr.close();
} catch (IOException e) {
System.out.println("文本文件读取流关闭失败!");
e.printStackTrace();
}
}
return sb.toString();

}
//访问SD卡
/* 1.得到当前设备SD卡的目录
*     Environment.getExternalStorageDirectory()
* */
//可下载各种文件
//返回 -1:代表下载文件出错        返回0:代表下载文件成功             返回 1:代表文件已经存在
//fileName代表你将要存入SD卡中的文件名,可以定义自己的文件名
public int downloadFile(String url,String path,String fileName){
InputStream in = null;
try {
File_Utils utils = new File_Utils() ;
//如果存在该文件了则返回1
if(utils.isFileExist(path+fileName)){
return 1;
}else{//否则则就获得否则则就通过调用File_Utils.java的write2SDFromInputStream函数写入SD卡中
in = getInputStreamFromUrl(url);
File resultFile = utils.write2SDFromInputStream(path, fileName, in);
if(resultFile == null){
return -1;
}
}

} catch (IOException e) {
e.printStackTrace();
return -1;
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
System.out.println("字节读取流关闭失败!");
e.printStackTrace();
}
}
}
return 0;
}

//将根据URL获取InputStream的功能封装起来,以便复用
public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
url = new URL(urlStr);
HttpURLConnection con =  (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream();
return in;
}
}


File_Utils.java

package zzl.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 File_Utils {
private String SDPATH;
public File_Utils(){
SDPATH = Environment.getExternalStorageDirectory()+"/";
}
//得到当前外部存储设备的目录
public String getSDPATH(){
return SDPATH;
}

//在SD卡上创建文件:
public File createSDFile(String dirAndFilename) throws IOException{
File file = new File(SDPATH+dirAndFilename);
file.createNewFile();
return file;
}

//在SD卡上创建目录
public File createSDDir(String dirName){
File dir = new File(SDPATH+dirName);
dir.mkdirs();
return dir;
}
//判断SD卡上的文件夹是否存在
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}

//将一个InputStream里面的数据写到SD卡中
public File write2SDFromInputStream(String path,String fileName,InputStream in){
File file = null;
OutputStream out = null;
try {
createSDDir(path);
try{file = createSDFile(path+fileName);}
catch(Exception e){
System.out.println("createSDFile 失败");
}

out = new FileOutputStream(file);
byte buf[] = new byte[1024*5];
int ch = 0;
while((ch = in.read(buf))!=-1){
out.write(buf);
}
out.flush();

} catch (IOException e) {
System.out.println("SD写入失败!");
e.printStackTrace();
}finally{
if(out!=null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("SD写入流关闭失败!");
}
}
return file;
}

}


总结:

1、要达到连接网络的效果,需要在download Manifest 中加入下面三句代码:

<uses-sdk android:minSdkVersion="4"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2、因为不是真正的连接到网路,测试的时候需要在cmd中输入adb shell 进行验证,当然这个的操作我们之前在SQlite那一节中介绍过了

3、总的整节视频看下来,总觉得还是很多东西没有消化的,很多mars老师自己写的东西,很多函数的调用还有一些不是很了解的,还是需要再研究一下的。

4、点击下载文本文件,效果如下:



而下载Mp3文件则还是有一定的bug,还需要再调试调试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: