1.文件下载的步骤
用到的类有Uri和HttpURLConnection
首先必须创建一个HttpURLConnection对象,实现代码如下:
<span style="white-space:pre"> </span>Uri url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
从urlConn对象获取一个InputStream对象
代码如下:
InputStream inputStream = urlConn.getInputStream();
在AndroidMainFest.xml文件中配置两个权限
一个是访问网络的权限,另外一个是访问SD卡的权限,用来存取文件
xml代码实现如下:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果不配置则可能下载报错或者根本无法获取输入流
2.下载文本文件
编写了一个方法download,返回值是String类型,保存文本文件所有的内容。代码实现如下
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();//定义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) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();//返回字符串
}
3.下载其他文件并写到sd卡之中
首先定义文件下载的工具类FileUtils,这个类可以作为一个通用的工具类来调用。以后可以直接拿来用。
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.mkdirs();
return dir;
}
/**
* 判断SD卡上的文件夹是否存在
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 将一个InputStream里面的数据写入到SD卡中
*/
public File write2SDFromInput(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;
}
}
实现方法定义如下:
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isFileExist(path + fileName)) {
return 1; //返回1代表文件已经存在
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path,fileName,inputStream); //传入的path格式为 xxx/,fileName格式 x.mp3
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 = urlConn.getInputStream();
return inputStream;
}
调用实例代码如下:
class DownloadTxtListener implements OnClickListener{
@Override
public void onClick(View v) {
HttpDownloader httpDownloader = new HttpDownloader();
String lrc = httpDownloader.download("http://192.168.1.107:8080/voa1500/a1.lrc");
System.out.println(lrc);
}
}
class DownloadMp3Listener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.downFile("http://192.168.1.107:8080/voa1500/a1.mp3", "voa/", "a1.mp3");
System.out.println(result);
}
}
通过以上代码可以实现文件的下载