标题很明显,这篇博文主要内容是:
在android程序中实现文件的下载并存储进手机或虚拟机的SD卡
在demo中我主要操作为:
1,根据有效的文本文件url地址,读取文本内容;demo使用的是.lrc格式的文件。
2,根据有效的文本文件url地址,把文件从网络地址下载,并放在手机SD卡中;demo使用的是.mp3文件。
很明显可以看出来两个demo用的文件是我们经常用到的,即是存储歌词和歌曲的两个文件,使用性强。
好了下面直接看过程,首先新建一个安卓项目,我这里定义为类DownloadActivity,很明显是一个下载demo,
大家看一下我项目的目录结构:
我用的版本是4.0的,图中画红色框的是需要编写代码的文件!下面给出文件的具体代码:
-------------------------------------- DownloadActivity.java
-----------------------------------
package com.senly.download;
import com.senly.utils.HttpDownloader;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class DownloadActivity extends Activity {
private Button downloadLRC = null;
private Button downloadMP3 = null;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
downloadLRC =
(Button)findViewById(R.id.downloadLRC);
downloadMP3 =
(Button)findViewById(R.id.downloadMP3);
downloadLRC.setOnClickListener(new
DownloadLRCListener());
downloadMP3.setOnClickListener(new
DownloadMP3Listener());
}
class DownloadLRCListener implements
OnClickListener{
@Override
public void onClick(View v)
{
new
MyThread(1).start();
}
}
class DownloadMP3Listener implements
OnClickListener{
@Override
public void onClick(View v)
{
new
MyThread(2).start();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_download,
menu);
return true;
}
class MyThread extends Thread{
private int flag = 0 ;
public MyThread(){}
public MyThread(int
flag){
this.flag =
flag;
}
@Override
public void run() {
if ( 1 ==
flag ) { // 基本文件下载
HttpDownloader
httpDownloader = new HttpDownloader();
String
contents = httpDownloader.downloadBaseFile("http://192.168.1.104:8081/CFM_xfire/I_Remember.lrc");
System.out.println(contents);
}
if ( 2 ==
flag ){ // 复杂文件下载及存储到手机SD卡
HttpDownloader
httpDownloader = new HttpDownloader();
int
resultInt = httpDownloader.downloadAllFile("http://192.168.1.104:8081/CFM_xfire/I_Remember.mp3","/downloadDir","/i_remember.mp3");
System.out.println(resultInt);
}
}
}
}
------------------------------------------ FileUtils.java
-----------------------------------
package com.senly.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;
import android.util.Log;
public class FileUtils {
private String SD_PATH;
public String getSD_PATH() {
return SD_PATH;
}
public FileUtils (){
//得到当前外部存储设备的目录
SD_PATH =
Environment.getExternalStorageDirectory() + "/";
}
public File createSDFile(String fileName) throws
IOException{
File file =
new File(SD_PATH + fileName);
file.createNewFile();
return file;
}
public File createSDDir(String dirName){
File dir = new File(SD_PATH +
dirName);
dir.mkdir();
return dir;
}
public boolean isFileExist(String
fileName){
File file = new File(SD_PATH +
fileName);
return file.exists();
}
public File write2SDFromInput(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];
while(input.read(buffer)
!= -1){
output.write(buffer);
}
//清掉缓存
output.flush(); } catch (Exception e) {
Log.e("write2SDFromInput",
e.getMessage());
} finally {
try {
if
(output != null){
output.close();
}
} catch
(IOException ioe){
Log.e("write2SDFromInput",
ioe.getMessage());
}
}
return file;
}
}
------------------------------------------
HttpDownloader.java -----------------------------------
package com.senly.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.MalformedURLException;
import java.net.URL;
public class HttpDownloader {
private URL url = null;
public String downloadBaseFile(String
urlStr){
StringBuffer sb = new
StringBuffer();
String line = null;
BufferedReader reader =
null;
try{
//创建一个url对象
url = new
URL(urlStr);
//通過url对象,创建一个HttpURLConnection对象(连接)
HttpURLConnection
urlConnection = (HttpURLConnection)url.openConnection();
//通过HttpURLConnection对象,得到InputStream
reader = new
BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
//使用io流读取文件
while ((line
= reader.readLine()) != null){
sb.append(line);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if
(reader != null){
reader.close();
}
} catch
(Exception e){
e.printStackTrace();
}
}
return sb.toString();
}
public int downloadAllFile(String urlStr,String
path, String fileName){
InputStream inputStream =
null;
try {
FileUtils
fileUtils = new FileUtils();
if
(fileUtils.isFileExist(path + fileName)){
return
1;
} else
{
inputStream
= getInputStream(urlStr);
File
file = fileUtils.write2SDFromInput(path, fileName,
inputStream);
if
( file == null ){
return
-1;
}
}
} catch (Exception e) {
e.printStackTrace();
return
-1;
} finally {
try {
if
(inputStream != null){
inputStream.close();
}
}catch
(Exception ioe){
ioe.printStackTrace();
}
}
return 0;
}
private InputStream getInputStream(String
urlStr)
throws
MalformedURLException,IOException {
url = new URL(urlStr);
HttpURLConnection
httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream =
httpURLConnection.getInputStream();
return inputStream;
} }
------------------------------ layout / activity_download.xml
---------------------------------
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DownloadActivity" >
android:id="@+id/myTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/myTextView" />
android:id="@+id/downloadLRC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/myTextView"
android:layout_marginTop="10dp"
android:text="@string/downloadLRC" />
android:id="@+id/downloadMP3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/downloadLRC"
android:layout_marginTop="10dp"
android:text="@string/downloadMP3" />
-------------------------------------- values / strings.xml
-----------------------------------
encoding="utf-8"?>
name="app_name">Download
Hello
world!
name="menu_settings">Settings
name="myTextView">下载文件
name="downloadLRC">downloadLRC
name="downloadMP3">downloadMP3
----------------------------------------
AndroidManifest.xml -----------------------------------
encoding="utf-8"?>
package="com.senly.download"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="14" />
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
android:name="android.permission.INTERNET"
>
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="com.senly.download.DownloadActivity"
android:label="@string/app_name" >
/>
android:name="android.intent.category.LAUNCHER"
/>
好的,到这里项目就算开发完了,不过你肯定有疑问,这下面两个url找不到啊!
没错,你肯定找不到,假如你只是想了解文件下载的实现,那么你直接到网络上找到两个文件地址代替就行了
可以跟我一样使用 .lrc 和 .mp3
文件,当然可以是其他文件,但是要注意“文件下载类HttpDownloader”中两个方法的执行范围:
1,对于 downloadBaseFile(String urlStr)
方法,是根据URL下载文件地址,前提是这个文件中的内容是文本类型。
2,对于 downloadAllFile(String urlStr,String path, String fileName)
方法, 是根据URL下载文件地址并把文件写入到SD卡,支持几乎大部分文件类型。
到这里,文章的大概目的就已经达到了!
(假如还没成功请往下看!)
结果是:
点击 downloadLRC 按钮,下载歌词文件,并打印出来!(会出现乱码,这是logcat的问题)
点击 downloadMP3 按钮 , 会打印 0 成功 ,1 已经存在 (我操作两次,所以显示1)
但是,假如在网上找不到这些文件的那该这么实验呢,我是如何把本地作为服务器的呢,很简单,接着看。
首先,使用 tomcat
,这个对于java开发人员来说,是熟悉得不过了的,非常有亲切感是吧!(当然你可以使用其他服务器)
找到tomcat安装目录下的conf文件夹中的server.xml文件,在中写上如下语句,部署项目如下:
path="/CFM_xfire">
ps:
1,docBase="E:\mywork\CFM_xfire"
指明项目路径
2,path="/CFM_xfire" 指明在浏览器上访问的地址
其中 CFM_xfire 是我的项目(随便新建一个java
web项目就行了),主要目的是存放 .lrc
和 .mp3 文件,目录如下(注意路径)
在tomcat上部署好之后,启动tomcat,在浏览器地址栏上可以尝试访问这两个地址(你是访问不了的,因为192.168.1.104是我联网的ip地址):
当然你访问这两个地址才是正确的,可能会更亲切:
或者
第一个会显示歌词信息,第二个会提示下载!
那为什么我在程序中会使用 192.168.1.104 因为安卓访问 127.0.0.1 和 localhost 会报错,因为它希望访问ip协议中的url地址!这一点请记住!庆幸的是,你假如看得了这篇文章,那么证明你正在上网,那么就换成你的ip就行了!
大家要是遇到什么解决不了的问题,请提出来一起解决!
如何查看文件是否已经下载在手机SD中,请看我另一篇文章!