Android作为一个手机操作系统,在Android中访问网络是许多应用程序都必需的功能。用户也经常需要在应用程序中下载所需要的文件比如电子书,MP3格式的音乐文件,电影等。
Android文件下载的一般步骤:
1、创建一个HttpURLConnection的对象
URL url=new URL(urlStr);
HtttpURLConnection urlConn=(HtttpURLConnection)url.OpenConnection();
2、获取一个InputStream输入流对象
urlConn.getInputStream();
3、在AndroidManifest.xml中添加网络访问权限
4、在AndroidManifest.xml中加入访问SDCard的权限
5、创建文件流FileOutputStream,将从InputStream读出的数据写入到FileOutputStream。
需要注意的是在Android3.0之前的Android平台上可以直接Activity所在的线程中访问网络,下载网络上的文件。但是这样的话,如果下载的文件较大,或者网速比较慢的情况下,Activity界面就会处于无法及时响应用户操作的状态。Android3.0中如果在Activity所在的线程访问网络,调试执行时会出现异常信息:“android.os.NetworkOnMainThreadException”,无法获取有效的HttpURLConnection对象。所以我们需要把访问网络,下载文件的操作放在另外的线程中。
示例:
新建一个Android应用程序项目。在main.xml总添加两个Button:buttontxt、buttonmp3。点击分别下载txt和mp3文件。下载的txt文件直接将txt文本文件的内容直接输出到控制台。mp3文件保存到虚拟结的SD卡目录下的Android文件夹中。为了下载方便,项目中下载的a.txt和music.mp3文件均放在本机安装的tomcat服务器上webapps目录下的Android文件夹中。
main.xml
- xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android&#61;"http://schemas.android.com/apk/res/android"
- android:orientation&#61;"vertical"
- android:layout_width&#61;"fill_parent"
- android:layout_height&#61;"fill_parent"
- >
- <TextView
- android:layout_width&#61;"fill_parent"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"&#64;string/hello"
- />
- <Button
- android:id&#61;"&#64;&#43;id/buttontxt"
- android:layout_width&#61;"300dp"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"单击下载txt文件"
- />
- <Button
- android:id&#61;"&#64;&#43;id/buttonmp3"
- android:layout_width&#61;"300dp"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"单击下载mp3文件"
- />
- LinearLayout>
- xml version&#61;"1.0" encoding&#61;"utf-8"?>
- <LinearLayout xmlns:android&#61;"http://schemas.android.com/apk/res/android"
- android:orientation&#61;"vertical"
- android:layout_width&#61;"fill_parent"
- android:layout_height&#61;"fill_parent"
- >
- <TextView
- android:layout_width&#61;"fill_parent"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"&#64;string/hello"
- />
- <Button
- android:id&#61;"&#64;&#43;id/buttontxt"
- android:layout_width&#61;"300dp"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"单击下载txt文件"
- />
- <Button
- android:id&#61;"&#64;&#43;id/buttonmp3"
- android:layout_width&#61;"300dp"
- android:layout_height&#61;"wrap_content"
- android:text&#61;"单击下载mp3文件"
- />
- LinearLayout>
Android_Download.java
- package idea.org;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- public class Android_Download extends Activity {
- private Button buttontxt;
- private Button buttonmp3;
-
- &#64;Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- buttontxt&#61;(Button)findViewById(R.id.buttontxt);
-
- buttontxt.setOnClickListener(new OnClickListener(){
-
-
-
-
- &#64;Override
- public void onClick(View v) {
-
-
- new Thread()
- {
- public void run()
- {
- HttpDownloader httpDownloader&#61;new HttpDownloader();
-
- String txt&#61;httpDownloader.download("http://172.24.24.20:8080/Android/a.txt");
- System.out.println(txt);
- }
- }.start();
- }
-
- });
- buttonmp3&#61;(Button)findViewById(R.id.buttonmp3);
-
- buttonmp3.setOnClickListener(new OnClickListener()
- {
-
-
-
-
- &#64;Override
- public void onClick(View v) {
-
- new Thread()
- {
- public void run()
- {
- try
- {
- HttpDownloader httpDownloader&#61;new HttpDownloader();
-
- intresult&#61;httpDownloader.download("http://172.24.24.20:8080/Android/music.mp3","Android/","music.mp3");
- System.out.println(result);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }.start();
-
- }
- });
- }
- }
- package idea.org;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- public class Android_Download extends Activity {
- private Button buttontxt;
- private Button buttonmp3;
-
- &#64;Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- buttontxt&#61;(Button)findViewById(R.id.buttontxt);
-
- buttontxt.setOnClickListener(new OnClickListener(){
-
-
-
-
- &#64;Override
- public void onClick(View v) {
-
-
- new Thread()
- {
- public void run()
- {
- HttpDownloader httpDownloader&#61;new HttpDownloader();
-
- String txt&#61;httpDownloader.download("http://172.24.24.20:8080/Android/a.txt");
- System.out.println(txt);
- }
- }.start();
- }
-
- });
- buttonmp3&#61;(Button)findViewById(R.id.buttonmp3);
-
- buttonmp3.setOnClickListener(new OnClickListener()
- {
-
-
-
-
- &#64;Override
- public void onClick(View v) {
-
- new Thread()
- {
- public void run()
- {
- try
- {
- HttpDownloader httpDownloader&#61;new HttpDownloader();
-
- int result&#61;httpDownloader.download("http://172.24.24.20:8080/Android/music.mp3","Android/","music.mp3");
- System.out.println(result);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }.start();
-
- }
- });
- }
- }
HttpDownloader.java
- package idea.org;
- 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.URL;
- public class HttpDownloader {
- private URL url&#61;null;
- public String download(String urlStr)
- {
- StringBuffer stringbuffer&#61;new StringBuffer();
- String line;
- BufferedReader bufferReader&#61;null;
- try
- {
-
- url&#61;new URL(urlStr);
-
- HttpURLConnection httpUrlConnection&#61;(HttpURLConnection) url.openConnection();
-
- bufferReader&#61;new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
- while((line&#61;bufferReader.readLine())!&#61;null)
- {
- stringbuffer.append(line);
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- return stringbuffer.toString();
-
- }
-
- public int download(String urlStr,String path,String fileName)
- {
- InputStream inputstream&#61;null;
- FileUtils fileUtils&#61;new FileUtils();
- if(fileUtils.isExist(path&#43;fileName))
- return 1;
- else
- {
- try {
- inputstream&#61;getFromUrl(urlStr);
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- File file&#61;fileUtils.writeToSDPATHFromInput(path, fileName, inputstream);
- if(file!&#61;null)
- return 0;
- else
- return -1;
- }
- }
-
- public InputStream getFromUrl(String urlStr) throws IOException
- {
- url&#61;new URL(urlStr);
- HttpURLConnection httpUrlConnection&#61;(HttpURLConnection) url.openConnection();
- InputStream input&#61;httpUrlConnection.getInputStream();
- return input;
- }
- }
- package idea.org;
- 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.URL;
- public class HttpDownloader {
- private URL url&#61;null;
- public String download(String urlStr)
- {
- StringBuffer stringbuffer&#61;new StringBuffer();
- String line;
- BufferedReader bufferReader&#61;null;
- try
- {
-
- url&#61;new URL(urlStr);
-
- HttpURLConnection httpUrlConnection&#61;(HttpURLConnection) url.openConnection();
-
- bufferReader&#61;new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
- while((line&#61;bufferReader.readLine())!&#61;null)
- {
- stringbuffer.append(line);
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- return stringbuffer.toString();
-
- }
-
- public int download(String urlStr,String path,String fileName)
- {
- InputStream inputstream&#61;null;
- FileUtils fileUtils&#61;new FileUtils();
- if(fileUtils.isExist(path&#43;fileName))
- return 1;
- else
- {
- try {
- inputstream&#61;getFromUrl(urlStr);
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- File file&#61;fileUtils.writeToSDPATHFromInput(path, fileName, inputstream);
- if(file!&#61;null)
- return 0;
- else
- return -1;
- }
- }
-
- public InputStream getFromUrl(String urlStr) throws IOException
- {
- url&#61;new URL(urlStr);
- HttpURLConnection httpUrlConnection&#61;(HttpURLConnection) url.openConnection();
- InputStream input&#61;httpUrlConnection.getInputStream();
- return input;
- }
- }
FileUtils.java
- package idea.org;
- 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&#61;null;
- public String getSDPATH()
- {
- return SDPATH;
- }
- public FileUtils()
- {
-
- SDPATH&#61;Environment.getExternalStorageDirectory()&#43;"/";
- }
-
- public File createFile(String fileName) throws IOException
- {
- File file&#61;new File(SDPATH&#43;fileName);
- file.createNewFile();
- return file;
- }
-
- public File createDir(String fileName) throws IOException
- {
- File dir&#61;new File(SDPATH&#43;fileName);
- dir.mkdir();
- return dir;
- }
-
- public boolean isExist(String fileName)
- {
- File file&#61;new File(SDPATH&#43;fileName);
- return file.exists();
- }
- public File writeToSDPATHFromInput(String path,String fileName,InputStream inputstream)
- {
- File file&#61;null;
- OutputStream outputstream&#61;null;
- try
- {
- createDir(path);
- file&#61;createFile(path&#43;fileName);
- outputstream&#61;new FileOutputStream(file);
- byte buffer[]&#61;new byte[1024];
-
- while((inputstream.read(buffer))!&#61;-1)
- {
- outputstream.write(buffer);
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- try {
- outputstream.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- return file;
- }
- }
- package idea.org;
- 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&#61;null;
- public String getSDPATH()
- {
- return SDPATH;
- }
- public FileUtils()
- {
-
- SDPATH&#61;Environment.getExternalStorageDirectory()&#43;"/";
- }
-
- public File createFile(String fileName) throws IOException
- {
- File file&#61;new File(SDPATH&#43;fileName);
- file.createNewFile();
- return file;
- }
-
- public File createDir(String fileName) throws IOException
- {
- File dir&#61;new File(SDPATH&#43;fileName);
- dir.mkdir();
- return dir;
- }
-
- public boolean isExist(String fileName)
- {
- File file&#61;new File(SDPATH&#43;fileName);
- return file.exists();
- }
- public File writeToSDPATHFromInput(String path,String fileName,InputStream inputstream)
- {
- File file&#61;null;
- OutputStream outputstream&#61;null;
- try
- {
- createDir(path);
- file&#61;createFile(path&#43;fileName);
- outputstream&#61;new FileOutputStream(file);
- byte buffer[]&#61;new byte[1024];
-
- while((inputstream.read(buffer))!&#61;-1)
- {
- outputstream.write(buffer);
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- try {
- outputstream.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- return file;
- }
- }
Android_Download Manifest.xml
- xml version&#61;"1.0" encoding&#61;"utf-8"?>
- <manifest xmlns:android&#61;"http://schemas.android.com/apk/res/android"
- package&#61;"idea.org"
- android:versionCode&#61;"1"
- android:versionName&#61;"1.0">
- <uses-sdk android:minSdkVersion&#61;"11" />
-
- <application android:icon&#61;"&#64;drawable/icon" android:label&#61;"&#64;string/app_name">
- <activity android:name&#61;".Android_Download"
- android:label&#61;"&#64;string/app_name">
- <intent-filter>
- <action android:name&#61;"android.intent.action.MAIN" />
- <category android:name&#61;"android.intent.category.LAUNCHER" />
- intent-filter>
- activity>
-
- application>
- <uses-permission android:name&#61;"android.permission.INTERNET"/>
- <uses-permission android:name&#61;"android.permission.WRITE_EXTERNAL_STORAGE"/>
- manifest>
- xml version&#61;"1.0" encoding&#61;"utf-8"?>
- <manifest xmlns:android&#61;"http://schemas.android.com/apk/res/android"
- package&#61;"idea.org"
- android:versionCode&#61;"1"
- android:versionName&#61;"1.0">
- <uses-sdk android:minSdkVersion&#61;"11" />
-
- <application android:icon&#61;"&#64;drawable/icon" android:label&#61;"&#64;string/app_name">
- <activity android:name&#61;".Android_Download"
- android:label&#61;"&#64;string/app_name">
- <intent-filter>
- <action android:name&#61;"android.intent.action.MAIN" />
- <category android:name&#61;"android.intent.category.LAUNCHER" />
- intent-filter>
- activity>
-
- application>
- <uses-permission android:name&#61;"android.permission.INTERNET"/>
- <uses-permission android:name&#61;"android.permission.WRITE_EXTERNAL_STORAGE"/>
- manifest>
运行结果&#xff1a;
界面
依次点击两个Button按钮之后控制台输出的信息。
a.txt文件中有中文&#xff0c;由于log日志只能输出英文字符&#xff0c;所以会出现乱码。现在mp3时输出download()方法的返回值0&#xff0c;说明下载成功。
如果这个时候我们再点击点击一次buttonmp3按钮&#xff0c;会输出返回值1&#xff0c;说明文件已经存在。
我们可以通过DDMS视图中的工具File Explorer查看虚拟机中SD卡目录中我们下载的文件。