Android应⽤软件开发(⼗⼀)⽂件下载使⽤Http协议下载⽂件,写⼊SD卡中
下载步骤:
1、创建⼀个HttpURLConnection对象
HttpURLConnection urlConn =
(HttpURLConnection )url.openConnection();
2、获得⼀个InputStream对象
3、设置⽹络访问权限(manifest⽂件中设置)
android.permission.INTERNET
访问SD卡:
1. 得到SD卡的⽬录
2. 访问SD卡的权限:
android.permission.WRITE_EXTERNAL_STORAGE
注意:⼀定不要忘记设置权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="schemas.android/apk/res/android"
package="mars.download"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".DownloadActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 设置⽹络下载权限和SD卡写⼊权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
DownloadActivity.java:
package mars.download;
import mars.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 DownloadActivity extends Activity {
/** Called when the activity is first created. */
private Button downloadTxtButton;
private Button downloadMp3Button;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
downloadTxtButton = (Button)findViewById(R.id.downloadTxt);
downloadMp3Button = (Button)findViewById(R.id.downloadMp3);
downloadTxtButton.setOnClickListener(new DownLoadTxtListener());
downloadMp3Button.setOnClickListener(new DownLoadMp3Listener());
}
class DownLoadTxtListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownloader httpDownloader = new HttpDownloader();
String str = httpDownloader.download("ishare.sina/download.php?action=loading&id=13912266&cid=05_14&p=1");  System.out.println("Download");
System.out.println(str);
}
}
class DownLoadMp3Listener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String urlStr = "ishare.sina/download.php?action=loading&id=13912266&cid=05_14&p=1";
HttpDownloader httpDownloader = new HttpDownloader();
int state = httpDownloader.downFile(urlStr, "voa/", "myFile");
System.out.println(state);
}
}
}
HttpDownloader.java:
package mars.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
public class HttpDownloader {
private URL url = null;
/**
* 根据URL下载⽂件
* 1. 创建⼀个URL对象
* 2. 通过URL对象,创建⼀个HttpURLConnection对象
* 3. 得到InputStream
* 4. 从InputStream当中读取数据
*/
//⽂本⽂件的下载
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();
java创建文件
//使⽤IO流读取数据
/**
* InputStream()得到的是字节流
* 套⼀层InputStreamReader得到的是字符流
* 在套⼀层BufferedReader得到的字符流就可以使⽤readLine按⾏读取数据了
*/
buffer = new BufferedReader(new InputStream()));
while((line = adLine())!=null){
sb.append(line);
}
}catch(Exception e){
System.out.println("Error");
e.printStackTrace();
}finally{
try{
buffer.close();
}catch(Exception e){
e.printStackTrace();
String();
}
//下载⽂件并写⼊到SD卡中
//参数:url地址,⽂件存储⽬录绝对路径,存储的⽂件名
public int downFile(String urlStr,String path,String fileName){
InputStream inputStream = null;
try{
FileUtils fileUtils = new FileUtils();
//如果⽂件已经存在则返回1
if(fileUtils.isFileExist(path+fileName)){
return 1;
}else{
//根据url地址得到⽂件输⼊流
inputStream = getInputStreamFromUrl(urlStr);
//将输⼊流写⼊SD卡,具体过程见FileUtils.java
File resultFile = fileUtils.writeSDFromInput(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);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();  InputStream inputStream = InputStream();
return inputStream;
}
}
FileUtils.java:
package mars.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;
/**
* 此类是操作SD卡⽂件的封装
* 包括判断⽂件(夹)是否存在,创建⽂件(夹),将⽂件流写⼊⽂件
*
* @author Administrator
*
*/
public class FileUtils {
//SD卡的路径名
private String SDPATH;
public String getSDPATH(){
return SDPATH;
}
public FileUtils(){
//得到当前外部存储设备的⽬录
SDPATH = ExternalStorageDirectory()+"/";
}
/**
* 在SD卡上创建⽂件
*
*/
public File createSDFile(String fileName)throws IOException{
//根据⽂件的全路径名得到⽂件对象
File file = new File(SDPATH + fileName);
//创建⽂件
return file;
/**
* 在SD卡上创建⽬录
*/
public File createSDDir(String dirName){
File dir = new File(SDPATH + dirName);
dir.mkdir();
return dir;
}
/**
* 判断⽂件夹是否存在
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
ists();
}
/**
* 将⼀个InputStream⾥⾯的数据写⼊到SD卡中
*/
//参数:⽂件存放路径(绝对⽬录路径),⽂件名,输⼊流
public File writeSDFromInput(String path,String fileName,InputStream input){  File file = null;
OutputStream output = null;
try{
//创建⽂件存储⽬录
createSDDir(path);
//创建⽂件
file = createSDFile(path+fileName);
//获取新建⽂件的输出流
output = new FileOutputStream(file);
//缓冲区
byte buffer [] = new byte[4 * 1024];
//从输⼊流中依次读⼊数据并输出到⽂件中,每次4个字节
while((ad(buffer))!= -1){
output.write(buffer);
}
//清空缓存
output.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
//关闭输出流
output.close();
}catch(Exception e){
e.printStackTrace();
}
}
return file;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。