今天和大家分享一下在android上怎么下载文件到手机上。
主要有两点大类容:
一,通过Http协议下载文件。
创建一个HttpURLConnection对象
- HttpURLConnection urlConn = (HttpURLConnection) url
- .openConnection();
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
获得一个InputStream对象
- inputStream = urlConn.getInputStream();
inputStream = urlConn.getInputStream();
访问网络的权限
- <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.INTERNET"/>
二,将下载的文件写入SDcard。
得到当前设备的SD卡目录
- Environment.getExternalStorageDirectory()
Environment.getExternalStorageDirectory()
设置访问SD卡的权限
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下面给出具体的代码:
DownLoad.java
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.HttpDownloader;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class DownLoad extends Activity {
- private Button textButton;
- private Button audioButton;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //文本下载
- textButton = (Button) findViewById(R.id.textButton);
- textButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- HttpDownloader http = new HttpDownloader();
- //注意这里不要用localhost或者127.0.0.1,会报错的,因为android里是10.0.2.2
- String txt = http
- .download("http://10.0.2.2:8080/examples/123123.txt");
- System.out.println(txt);
- }
- });
- //音频下载
- audioButton = (Button) findViewById(R.id.audioButton);
- audioButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- HttpDownloader http = new HttpDownloader();
- String result = http.download(
- "http://10.0.2.2:8080/examples/123.mp3", "/music",
- "zhou.mp3");
- System.out.println(result);
- }
- });
- }
- }
import android.app.Activity;
import android.os.Bundle;
import android.util.HttpDownloader;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownLoad extends Activity {
private Button textButton;
private Button audioButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//文本下载
textButton = (Button) findViewById(R.id.textButton);
textButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
HttpDownloader http = new HttpDownloader();
//注意这里不要用localhost或者127.0.0.1,会报错的,因为android里是10.0.2.2
String txt = http
.download("http://10.0.2.2:8080/examples/123123.txt");
System.out.println(txt);
}
});
//音频下载
audioButton = (Button) findViewById(R.id.audioButton);
audioButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
HttpDownloader http = new HttpDownloader();
String result = http.download(
"http://10.0.2.2:8080/examples/123.mp3", "/music",
"zhou.mp3");
System.out.println(result);
}
});
}
}
FileUtil.java
- 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 FileUtil {
- private String SDCARDPATH;
- public String getSDCARDPATH() {
- return SDCARDPATH;
- }
- public FileUtil() {
- // 得到手机存储器目录---因为各个厂商的手机SDcard可能不一样,最好不要写死了
- SDCARDPATH = Environment.getExternalStorageDirectory() + "/";
- }
- /**
- * 在SDcard上创建文件
- *
- * @param fileName
- * @return File
- */
- public File creatSDFile(String fileName) {
- File file = new File(SDCARDPATH + fileName);
- return file;
- }
- /**
- * 在SDcard上创建目录
- *
- * @param dirName
- */
- public void createSDDir(String dirName) {
- File file = new File(SDCARDPATH + dirName);
- file.mkdir();
- }
- /**
- * 判断文件是否存在
- *
- * @param fileName
- * @return boolean
- */
- public boolean isFileExist(String fileName) {
- File file = new File(SDCARDPATH + fileName);
- return file.exists();
- }
- /**
- * @param path
- * 存放目录
- * @param fileName
- * 文件名字
- * @param input
- * 数据来源
- * @return
- */
- public File writeToSDCard(String path, String fileName, InputStream input) {
- File file = null;
- OutputStream output = null;
- try {
- //创建路径
- createSDDir(path);
- //创建文件
- file = creatSDFile(path + fileName);
- output = new FileOutputStream(file);
- //以4K为单位,每次写4k
- byte buffer[] = new byte[4 * 1024];
- while ((input.read(buffer)) != -1) {
- output.write(buffer);
- }
- // 清除缓存
- output.flush();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- // 关闭流
- output.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return file;
- }
- }
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 FileUtil {
private String SDCARDPATH;
public String getSDCARDPATH() {
return SDCARDPATH;
}
public FileUtil() {
// 得到手机存储器目录---因为各个厂商的手机SDcard可能不一样,最好不要写死了
SDCARDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SDcard上创建文件
*
* @param fileName
* @return File
*/
public File creatSDFile(String fileName) {
File file = new File(SDCARDPATH + fileName);
return file;
}
/**
* 在SDcard上创建目录
*
* @param dirName
*/
public void createSDDir(String dirName) {
File file = new File(SDCARDPATH + dirName);
file.mkdir();
}
/**
* 判断文件是否存在
*
* @param fileName
* @return boolean
*/
public boolean isFileExist(String fileName) {
File file = new File(SDCARDPATH + fileName);
return file.exists();
}
/**
* @param path
* 存放目录
* @param fileName
* 文件名字
* @param input
* 数据来源
* @return
*/
public File writeToSDCard(String path, String fileName, InputStream input) {
File file = null;
OutputStream output = null;
try {
//创建路径
createSDDir(path);
//创建文件
file = creatSDFile(path + fileName);
output = new FileOutputStream(file);
//以4K为单位,每次写4k
byte buffer[] = new byte[4 * 1024];
while ((input.read(buffer)) != -1) {
output.write(buffer);
}
// 清除缓存
output.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭流
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}
HttpDownloader.java
- 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;
- public class HttpDownloader {
- private URL url = null;
- /**
- * 下载文本文件
- *
- * @param urlStr
- * @return
- */
- public String download(String urlStr) {
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null;
- try {
- buffer = new BufferedReader(new InputStreamReader(
- getInputStreamFromUrl(urlStr)));
- //一行一行的读取
- while ((line = buffer.readLine()) != null) {
- sb.append(line);
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- buffer.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
- /**
- * @param urlStr
- * 文件所在的网络地址
- * @param path
- * 存储的目录
- * @param fileName
- * 存放的文件名
- * @return 状态
- */
- public String download(String urlStr, String path, String fileName) {
- InputStream inputStream = null;
- try {
- FileUtil fileUtils = new FileUtil();
- //判断文件是否已存在
- if (fileUtils.isFileExist(path + fileName)) {
- return "fileExist";
- } else {
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.writeToSDCard(path, fileName,
- inputStream);
- //如果resultFile==null则下载失败
- if (resultFile == null) {
- return "downloadError";
- }
- }
- } catch (Exception e) {
- //如果异常了,也下载失败
- e.printStackTrace();
- return "downloadError";
- } finally {
- try {
- //别忘了关闭流
- inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return "downloadOk";
- }
- /**
- * 连接到网络( 抽取的公共方法)
- *
- * @param urlStr
- * 文件所在的网络地址
- * @return InputStream
- */
- public InputStream getInputStreamFromUrl(String urlStr) {
- InputStream inputStream = null;
- try {
- // 创建一个URL对象
- url = new URL(urlStr);
- // 根据URL对象创建一个HttpURLConnection连接
- HttpURLConnection urlConn = (HttpURLConnection) url
- .openConnection();
- // IO流读取数据
- inputStream = urlConn.getInputStream();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return inputStream;
- }
- }
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;
public class HttpDownloader {
private URL url = null;
/**
* 下载文本文件
*
* @param urlStr
* @return
*/
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
buffer = new BufferedReader(new InputStreamReader(
getInputStreamFromUrl(urlStr)));
//一行一行的读取
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* @param urlStr
* 文件所在的网络地址
* @param path
* 存储的目录
* @param fileName
* 存放的文件名
* @return 状态
*/
public String download(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtil fileUtils = new FileUtil();
//判断文件是否已存在
if (fileUtils.isFileExist(path + fileName)) {
return "fileExist";
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.writeToSDCard(path, fileName,
inputStream);
//如果resultFile==null则下载失败
if (resultFile == null) {
return "downloadError";
}
}
} catch (Exception e) {
//如果异常了,也下载失败
e.printStackTrace();
return "downloadError";
} finally {
try {
//别忘了关闭流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "downloadOk";
}
/**
* 连接到网络( 抽取的公共方法)
*
* @param urlStr
* 文件所在的网络地址
* @return InputStream
*/
public InputStream getInputStreamFromUrl(String urlStr) {
InputStream inputStream = null;
try {
// 创建一个URL对象
url = new URL(urlStr);
// 根据URL对象创建一个HttpURLConnection连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// IO流读取数据
inputStream = urlConn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="android.apps"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".DownLoad"
- 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>
- <!-- 连接到网络的权限 -->
- <uses-permission android:name="android.permission.INTERNET"/>
- <!-- 访问SDcard的权限 -->
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- </manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.apps"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".DownLoad"
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>
<!-- 连接到网络的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 访问SDcard的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
希望对大家有帮助。