一、使用HTTP协议下载文件
文件下载步骤:
1) 创建一个HttpURLConnection对象
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
2) 获得一个InputStream对象
urlConnection.getInputStream();
3) 获得网络权限
android.permission.INTERNET
二、将下载的文件写入SD Card
1) 得到当前设备SD卡的目录
Environment.getExternalStorageDirectory();
2) 访问SD卡的权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
三、测试程序
DownloadActivity.java
package com.android.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.android.utils.HttpDownloader;
public class DownloadActivity extends Activity {
private Button downloadfile = null;
private Button downloadmp3 = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadfile = (Button)findViewById(R.id.downloadfile);
downloadmp3 = (Button)findViewById(R.id.downloadmp3);
downloadfile.setText(R.string.downloadfile);
downloadmp3.setText(R.string.downloadmp3);
downloadfile.setOnClickListener(new DownloadFileListener());
downloadmp3.setOnClickListener(new DownloadMP3Listener());
}
class DownloadFileListener implements OnClickListener{
public void onClick(View v) {
HttpDownloader httpDownloader = new HttpDownloader();
String txt = httpDownloader.download("http://221.206.235.201:8080/download/panghuang.txt");
System.out.println(txt);
}
}
class DownloadMP3Listener implements OnClickListener{
public void onClick(View v){
HttpDownloader httpDownloader = new HttpDownloader();
int downloadResult = httpDownloader.downloadFile("http://221.206.235.201:8080/download/lovestory.mp3","TaylorSwift/","lovestory.mp3");
System.out.println(downloadResult);
}
}
}
HttpDownloader.java
package com.android.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownloader {
private URL url = null;
/**
* 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容
* 1.创建一个URL对象
* 2.通过URL对象,创建一个HttpURLConnection对象
* 3.得到InputStram
* 4.从InputStream当中读取数据
* @param url
* @return
*/
public String download(String fileURL){
StringBuffer stringBuffer = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try{
//创建一个URL对象
url = new URL(fileURL);
//创建一个HTTP连接
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//使用IO流读取数据
buffer = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while((line = buffer.readLine()) != null){
stringBuffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
}
return stringBuffer.toString();
}
/**
* 可以下载任意文件,返回-1代表下载出错,返回0代表下载成功,返回1代表文件已存在
* 参数为源URL地址、目标路径、文件名
*/
public int downloadFile(String fileURL,String path,String fileName){
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {
url = new URL(fileURL);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
inputStream = urlConnection.getInputStream();
File resultFile = fileUtils.writeToSDFromInput(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;
}
}
FileUtils.java
package com.android.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() {
//得到当前外部存储设备的目录,得到的目录名/SDCARD
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SD卡上创建文件
* @throws IOException
*/
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上创建目录
* @param dirName
*/
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 writeToSDFromInput(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);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return file;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadfile"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadmp3"
/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.activity"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".DownloadActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 在SDCard中创建与删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
应该注意的问题:
本来嘛,文件下载很简单,无非记住上面的几个步骤,外加IO的一些知识,但是就这么个小程序会有很多让人头疼的问题。
1. 首先,在manifest.xml文件中一定要加入对SD卡操作的权限,这点只要是文件下载都会提到,但是这个权限加在哪个标签里一定要注意,最初片面的认为哪个Activity访问,则把权限加在哪个Activity的标签里,结果出错了,好久好久才找到,应该是加在manifest标签里的!
2. 其次,是访问Tomcat中文件的URL问题,一定不要用localhost或127.0.0.1,因为是在模拟器上访问电脑本机,当前的localhost指的是模拟器而不是电脑本机。要想访问tomcat上的文件,一定要加上电脑本机的IP地址。
3. 最后,URL中不能有中文,不能有空格,否则就是郁闷死了也找不到!
总之细节决定成败!
运行结果:
tomcat中的文件: