首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android利用Http上载文件

2012-09-18 
Android利用Http下载文件Android利用Http下载文件一、场景?? 下载存文本文件和下载如mp3等大容量的文件界面

Android利用Http下载文件

Android利用Http下载文件

一、场景

?? 下载存文本文件和下载如mp3等大容量的文件

界面


Android利用Http上载文件

二、代码编写

?1.AndroidMainfest.xml中配置

主要是解决网络权限和写SDCard的权限

?

?

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="linys.download" android:versionCode="1" android:versionName="1.0"><uses-sdk android:minSdkVersion="8" /><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><!-- 访问网络和操作SD卡 加入的两个权限配置 --><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></manifest>
?

2.Activity编写

?利用Http协议下载文件并存储到SDCard
??? 1.创建一个URL对象
??? 2.通过URL对象,创建一个HttpURLConnection对象
??? 3.得到InputStream
??? 4.从InputStream当中读取数据
??? 存到SDCard
??? 1.取得SDCard路径
??? 2.利用读取大文件的IO读法,读取文件

package linys.download;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;/** *  * @Project: Android_MyDownload * @Desciption: 利用Http协议下载文件并存储到SDCard 1.创建一个URL对象2.通过URL对象,创建一个HttpURLConnection对象3.得到InputStream4.从InputStream当中读取数据存到SDCard1.取得SDCard路径2.利用读取大文件的IO读法,读取文件 *  * @Author: LinYiSong * @Date: 2011-3-25~2011-3-25 */public class MyDownload extends Activity {private Button downFileBtn;private Button downMP3Btn;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                downFileBtn=(Button)this.findViewById(R.id.downFile);        downMP3Btn=(Button)this.findViewById(R.id.downMP3);                downFileBtn.setOnClickListener(new DownFileClickListener());        downMP3Btn.setOnClickListener(new DownMP3ClickListener());    }        /**     *      * @Project: Android_MyDownload     * @Desciption: 只能读取文本文件,读取mp3文件会出现内存溢出现象     * @Author: LinYiSong     * @Date: 2011-3-25~2011-3-25     */    class DownFileClickListener implements OnClickListener{@Overridepublic void onClick(View v) {String urlStr="http://172.17.54.91:8080/download/down.txt";try {/* * 通过URL取得HttpURLConnection * 要网络连接成功,需在AndroidMainfest.xml中进行权限配置 * <uses-permission android:name="android.permission.INTERNET" /> */URL url=new URL(urlStr);HttpURLConnection conn=(HttpURLConnection)url.openConnection();//取得inputStream,并进行读取InputStream input=conn.getInputStream();BufferedReader in=new BufferedReader(new InputStreamReader(input));String line=null;StringBuffer sb=new StringBuffer();while((line=in.readLine())!=null){sb.append(line);}System.out.println(sb.toString());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}    }    /**     *      * @Project: Android_MyDownload     * @Desciption: 读取任意文件,并将文件保存到手机SDCard     * @Author: LinYiSong     * @Date: 2011-3-25~2011-3-25     */    class DownMP3ClickListener implements OnClickListener{@Overridepublic void onClick(View v) {String urlStr="http://172.17.54.91:8080/download/1.mp3";String path="file";String fileName="2.mp3";OutputStream output=null;try {/* * 通过URL取得HttpURLConnection * 要网络连接成功,需在AndroidMainfest.xml中进行权限配置 * <uses-permission android:name="android.permission.INTERNET" /> */URL url=new URL(urlStr);HttpURLConnection conn=(HttpURLConnection)url.openConnection();//取得inputStream,并将流中的信息写入SDCard/* * 写前准备 * 1.在AndroidMainfest.xml中进行权限配置 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> * 取得写入SDCard的权限 * 2.取得SDCard的路径: Environment.getExternalStorageDirectory() * 3.检查要保存的文件上是否已经存在 * 4.不存在,新建文件夹,新建文件 * 5.将input流中的信息写入SDCard * 6.关闭流 */String SDCard=Environment.getExternalStorageDirectory()+"";String pathName=SDCard+"/"+path+"/"+fileName;//文件存储路径File file=new File(pathName);InputStream input=conn.getInputStream();if(file.exists()){System.out.println("exits");return;}else{String dir=SDCard+"/"+path;new File(dir).mkdir();//新建文件夹file.createNewFile();//新建文件output=new FileOutputStream(file);//读取大文件byte[] buffer=new byte[4*1024];while(input.read(buffer)!=-1){output.write(buffer);}output.flush();}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {output.close();System.out.println("success");} catch (IOException e) {System.out.println("fail");e.printStackTrace();}}}        }}
?

?

?

byte[] buffer=new byte[4*1024]; while(input.read(buffer)!=-1){ output.write(buffer); } output.flush();


读取流的时候,读取多少length 写多少length,对吧?
你自己试过吗?难道的文件长度 都刚好是 4*1024的整数倍? 2 楼 dampce032 2011-03-31   只是设定下缓冲的大小,你可以修改,和文件的大小无关 3 楼 strong46066999 2011-11-12   哥哥,你这代码,1楼老兄,已经说了,文件存储的时候,会多出很多无用的字节,
小弟不才,修修改改,是这样的。

byte[] buffer = new byte[4 * 1024];
int len;
while ((len=input.read(buffer))!= -1) {
output.write(buffer,0,len);
}

热点排行