转载自:http://blog.csdn.net/chichoxian/article/details/8566481
1.主要内容
2.文件下载的主要步骤
![Android文件的下载_sd卡](https://img-my.csdn.net/uploads/201302/01/1359719639_4484.jpg)
3.实际操作
![Android文件的下载_sd卡_02](https://img-my.csdn.net/uploads/201302/03/1359824838_2420.jpg)
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <Button
- android:id="@+id/downloadTxt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载文本文件"
- />
- <Button
- android:id="@+id/downloadMp3"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载MP3文件 "
- />
- </LinearLayout>
- public String download(String urlStr){
- //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null; //使用它可以每次读取一行文件
- try{
- //创建一个URL的对象
- url = new URL(urlStr);
- //创建一个HTTP链接
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- 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();
- }
在这里我们使用
buffer = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
BufferedReader buffer = null;
这样我们可以每次都读取一行。sb对象中存储了有关的下载内容,最后作为返回值 使用HttpURLConnection 来建立连接
在这里使用了java的IO流,他使用了装饰着设计模式,urlConn存储的是网络上的资源的地址,我们通过getInputStream来建立了一条“管道”,把他所指的地址的内容导入到我们的程序中。
在这里,getInutStream的到的是字节流,这个时候通过inputStreamReader转换为字符流,再通过BuffererReader一步步的扩大。由于使用的是BufferReader所以可以一行行的读取。我们
使用了
while((line =buffer.readLine())!= null){
sb.append(line);
}
当读到文件的末尾的时候就结束.注意使用异常处理来读取。
这里使用了标准的java异常处理函数格式:
try{
....
}catch(Exception e){
...
}finally{
//Do
}
注意:1.以上方法只适用于读取文本文件,读取MP3文件还需要重写方法。
2、android是基于权限的,所以要记得在AndroidManifest.xml注册。要得到当前设备SD卡的目录我们使用:Environment.getExternalStorageDirectory(),得到外部存储设备。注意不要把目录写死
访问SD卡的权限:android.permission.WRITE_EXTERNAL_STORAGE
之后我们来看另一个类:
- package grace.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.getExternalStorageState() + "/";
- }
- /**
- * 在SD卡上创建目录
- */
- public File createSDDir(String dirName){
- File dir = new File(SDPATH +dirName);
- dir.mkdir();
- return dir;
- }
- /***
- * 在SD卡上创建文件
- *
- * @throws IOException
- */
- public File createSDFile(String fileName) throws IOException{
- File file = new File(SDPATH +fileName);
- file.createNewFile();
- return file;
- }
- /**
- * 判断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{
- 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){
- e.printStackTrace();
- }
- finally{
- try{
- output.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return file;
- }
- }
现在我们在创建一个方法,使inputStream里的数据写入到SDCARD中我们制定的地方。这是我们创建方法:
public File write2SDFromInput(String path,String fileName, InputStream input)
这个函数的第一个形参指的就是我们指定的存储路径,第二个参数指的就是文件名,inputStream实质上就是我们在HttpDownloader类当中所保存的数据。现在我们要把它写进sdcard当中。
我们创建一个file对象调用我们刚才写的方法,在创建一个outPutStream对象。
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();
这里我们创建一个输出流让它对准文件,向其中写入我们要写的数据。
这里用到了一个过渡,那就是buffer,先从输入流中读入数据到一个缓冲区,在冲缓冲区中把数据读出写入到文件当中去。
要记得清空缓冲流,判断是不是有异常。
之后我们再来看HttpDownloader这个类当中的另一个方法:
- /**
- * 下载任意形式的文件
- */
- //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名
- public int downFile(String urlStr, String path,String fileName){
- InputStream inputStream = null;
- try{
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path +fileName)){
- return 1 ;
- }
- else{
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.write2SDFromInput(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;
- }
这个函数我们用它来读取MP3格式的文件。这个方法的返回值是整形。该函数返回整形 -1:代表下载文件出错 ,0:代表下载文件成功 ,1:代表文件已经存在。
第一个参数是想要下载的文件参数地址也就是下载的网址,第二个为存放的位置,第三个为你自己取的文件名
publicint downFile(String urlStr, String path,String fileName)
我们用刚才写好的类来判断要下载的文件是否已经存在。
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path+fileName)){
- return1 ;
- }
如果存在返回1.
inputStream =getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
要是文件不存在我们就调用getInoutStreamFromUrl方法获得想要下载的文件的网址。
- private InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException,IOException {
- // TODO Auto-generated method stub
- url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- InputStream inputStream =urlConn.getInputStream();
- return inputStream;
- }
- }
这个函数是我们自己写的,和刚才download函数很像。
这个时候我们来看一下HttpDownloader类的全貌:- package grace.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;
- /***
- * 根据URL下载文件
- * @param
- * @return
- */
- public String download(String urlStr){
- //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null; //使用它可以每次读取一行文件
- try{
- //创建一个URL的对象
- url = new URL(urlStr);
- //创建一个HTTP链接
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- 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();
- }
- /**
- * 下载任意形式的文件
- */
- //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名
- public int downFile(String urlStr, String path,String fileName){
- InputStream inputStream = null;
- try{
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path +fileName)){
- return 1 ;
- }
- else{
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.write2SDFromInput(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;
- }
- private InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException,IOException {
- // TODO Auto-generated method stub
- url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- InputStream inputStream =urlConn.getInputStream();
- return inputStream;
- }
- }
下面我们来看一下DownLoad这个类的实现情况:
- package com.example.download01;
- import grace.utils.HttpDownloader;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class Download extends Activity {
- private Button downloadTxtButton;
- private Button downloadMp3Button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- downloadTxtButton = (Button)findViewById(R.id.downloadTxt);
- downloadMp3Button = (Button)findViewById(R.id.downloadMp3);
- downloadTxtButton.setOnClickListener(new DownloadTxtListener());
- downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
- }
- class DownloadTxtListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- 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);
- }
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }
这样整个下载功能就已经实现了。
1.主要内容
2.文件下载的主要步骤
![Android文件的下载_sd卡](https://img-my.csdn.net/uploads/201302/01/1359719639_4484.jpg)
3.实际操作
![Android文件的下载_sd卡_02](https://img-my.csdn.net/uploads/201302/03/1359824838_2420.jpg)
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
- <Button
- android:id="@+id/downloadTxt"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载文本文件"
- />
- <Button
- android:id="@+id/downloadMp3"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="下载MP3文件 "
- />
- </LinearLayout>
- public String download(String urlStr){
- //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null; //使用它可以每次读取一行文件
- try{
- //创建一个URL的对象
- url = new URL(urlStr);
- //创建一个HTTP链接
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- 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();
- }
在这里我们使用
buffer = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));
BufferedReader buffer = null;
这样我们可以每次都读取一行。sb对象中存储了有关的下载内容,最后作为返回值 使用HttpURLConnection 来建立连接
在这里使用了java的IO流,他使用了装饰着设计模式,urlConn存储的是网络上的资源的地址,我们通过getInputStream来建立了一条“管道”,把他所指的地址的内容导入到我们的程序中。
在这里,getInutStream的到的是字节流,这个时候通过inputStreamReader转换为字符流,再通过BuffererReader一步步的扩大。由于使用的是BufferReader所以可以一行行的读取。我们
使用了
while((line =buffer.readLine())!= null){
sb.append(line);
}
当读到文件的末尾的时候就结束.注意使用异常处理来读取。
这里使用了标准的java异常处理函数格式:
try{
....
}catch(Exception e){
...
}finally{
//Do
}
注意:1.以上方法只适用于读取文本文件,读取MP3文件还需要重写方法。
2、android是基于权限的,所以要记得在AndroidManifest.xml注册。要得到当前设备SD卡的目录我们使用:Environment.getExternalStorageDirectory(),得到外部存储设备。注意不要把目录写死
访问SD卡的权限:android.permission.WRITE_EXTERNAL_STORAGE
之后我们来看另一个类:
- package grace.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.getExternalStorageState() + "/";
- }
- /**
- * 在SD卡上创建目录
- */
- public File createSDDir(String dirName){
- File dir = new File(SDPATH +dirName);
- dir.mkdir();
- return dir;
- }
- /***
- * 在SD卡上创建文件
- *
- * @throws IOException
- */
- public File createSDFile(String fileName) throws IOException{
- File file = new File(SDPATH +fileName);
- file.createNewFile();
- return file;
- }
- /**
- * 判断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{
- 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){
- e.printStackTrace();
- }
- finally{
- try{
- output.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return file;
- }
- }
现在我们在创建一个方法,使inputStream里的数据写入到SDCARD中我们制定的地方。这是我们创建方法:
public File write2SDFromInput(String path,String fileName, InputStream input)
这个函数的第一个形参指的就是我们指定的存储路径,第二个参数指的就是文件名,inputStream实质上就是我们在HttpDownloader类当中所保存的数据。现在我们要把它写进sdcard当中。
我们创建一个file对象调用我们刚才写的方法,在创建一个outPutStream对象。
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();
这里我们创建一个输出流让它对准文件,向其中写入我们要写的数据。
这里用到了一个过渡,那就是buffer,先从输入流中读入数据到一个缓冲区,在冲缓冲区中把数据读出写入到文件当中去。
要记得清空缓冲流,判断是不是有异常。
之后我们再来看HttpDownloader这个类当中的另一个方法:
- /**
- * 下载任意形式的文件
- */
- //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名
- public int downFile(String urlStr, String path,String fileName){
- InputStream inputStream = null;
- try{
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path +fileName)){
- return 1 ;
- }
- else{
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.write2SDFromInput(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;
- }
这个函数我们用它来读取MP3格式的文件。这个方法的返回值是整形。该函数返回整形 -1:代表下载文件出错 ,0:代表下载文件成功 ,1:代表文件已经存在。
第一个参数是想要下载的文件参数地址也就是下载的网址,第二个为存放的位置,第三个为你自己取的文件名
publicint downFile(String urlStr, String path,String fileName)
我们用刚才写好的类来判断要下载的文件是否已经存在。
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path+fileName)){
- return1 ;
- }
如果存在返回1.
inputStream =getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
要是文件不存在我们就调用getInoutStreamFromUrl方法获得想要下载的文件的网址。
- private InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException,IOException {
- // TODO Auto-generated method stub
- url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- InputStream inputStream =urlConn.getInputStream();
- return inputStream;
- }
- }
这个函数是我们自己写的,和刚才download函数很像。
这个时候我们来看一下HttpDownloader类的全貌:- package grace.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;
- /***
- * 根据URL下载文件
- * @param
- * @return
- */
- public String download(String urlStr){
- //在这里设置一个形参它用来保存下载的文本文件中的所有内容,它用于下载任何类型的文本文件
- StringBuffer sb = new StringBuffer();
- String line = null;
- BufferedReader buffer = null; //使用它可以每次读取一行文件
- try{
- //创建一个URL的对象
- url = new URL(urlStr);
- //创建一个HTTP链接
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- 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();
- }
- /**
- * 下载任意形式的文件
- */
- //第一个参数是想要下载的文件参数地址,第二个为存放的位置,第三个为你自己取的文件名
- public int downFile(String urlStr, String path,String fileName){
- InputStream inputStream = null;
- try{
- FileUtils fileUtils = new FileUtils();
- if(fileUtils.isFileExist(path +fileName)){
- return 1 ;
- }
- else{
- inputStream = getInputStreamFromUrl(urlStr);
- File resultFile = fileUtils.write2SDFromInput(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;
- }
- private InputStream getInputStreamFromUrl(String urlStr)
- throws MalformedURLException,IOException {
- // TODO Auto-generated method stub
- url = new URL(urlStr);
- HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
- InputStream inputStream =urlConn.getInputStream();
- return inputStream;
- }
- }
下面我们来看一下DownLoad这个类的实现情况:
- package com.example.download01;
- import grace.utils.HttpDownloader;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class Download extends Activity {
- private Button downloadTxtButton;
- private Button downloadMp3Button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- downloadTxtButton = (Button)findViewById(R.id.downloadTxt);
- downloadMp3Button = (Button)findViewById(R.id.downloadMp3);
- downloadTxtButton.setOnClickListener(new DownloadTxtListener());
- downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
- }
- class DownloadTxtListener implements OnClickListener{
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- 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);
- }
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }
这样整个下载功能就已经实现了。