【网学网提醒】:网学会员为需要朋友们搜集整理了android之网络文件下载保存到SD_card上相关资料,希望对各位网友有所帮助!
android之网络文件
下载保存到SDcard上
1.操作SDcard要注意的地方:(1)要访问SDcard,在AndroidManifest.xml文件中需要申请权限-permission
(2)手机模拟器中要有SDcard,没有的话请创建命令行创建SDcard:mksdcard
filepath例:mksdcard2048mc:\sdcard.img(3)将手机SDcard的镜像文件与创建的AVD绑定2.核心操作代码:(1)判断SDcard是否存在StringEnvironment.getExternalStorageState();//外部存储设备的状态若结果是Environment.MEDIA_MOUNTED则说明存在可读写(2)获得SDcard目录Environment.getExternalStorageDirectory();(3)访问网络1.创建HttpURLConnection对象HttpURLConnectionurlCon=(HttpURLConnection)url.openConnection();2.获得一个InputStream对象urlCon.getInputStream();
一个案例的全部步骤及原代码,图片:1.首先要在硬盘上创建一个SDcard的虚拟镜像文件:(确保系统中已经配置了Androidsdk的tools的路径到PATH中)mksdcard2048mc:\sdcard.img//2048m表示2048MB大小c:\sdcard.img:表示文件位置2.在创建AVD时,指定SDcard的位置
现在AVD中就有SDcard了.3.在tomcat中布置一个项目,里面有a.txt文件,用于下载的,接着将服务器启动起来,测试访问一下。我的是:localhost:8081/downloadfile/a.txt4.在eclipse中创建一个android项目.5.在AndroidMenifext.xml文件中加入以下配置
6.在layout目录下的main.xml中配置两个按钮:7.编写一个FileUtils类
packagecom.accp.util.file;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importandroid.os.Environment;publicclassFileUtils{privateStringSDPATH;//用于存sdcard的文件的路径publicStringgetSDPATH(){returnSDPATH;}publicvoidsetSDPATH(StringsDPATH){SDPATH=sDPATH;}
/***构造方法*获取SD卡
路径*/publicFileUtils(){//获得当前外部存储设备的目录SDPATH=Environment.getExternalStorageDirectory()+"/";System.out.println("sdcard'sdirectorypath:"+SDPATH);}
/***在SD卡上创建文件*@throwsIOException*/
publicFilecreateSDFile(StringfileName)throwsIOException{Filefile=newFile(SDPATH+fileName);file.createNewFile();returnfile;}/***在SD卡上创建目录*/publicFilecreateSDDir(StringdirName){Filedir=newFile(SDPATH+dirName);System.out.println("storagedevice'sstate:"+Environment.getExternalStorageState());if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){System.out.println("thisdirectoryrealpathis:"+dir.getAbsolutePath());System.out.println("theresultofmakingdirectory:"+dir.mkdir());}returndir;}/***判断SD卡上的文件夹是否存在*/publicbooleanisFileExist(StringfileName){Filefile=newFile(SDPATH+fileName);returnfile.exists();}/***将一个inputSteam里面的数据写入到SD卡中*/publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminputStream){Filefile=null;OutputStreamoutput=null;try{//创建SD卡上的目录Filetempf=createSDDir(path);System.out.println("directoryinthesdcard:"+tempf.exists());file=createSDFile(path+fileName);System.out.println("fileinthesdcard:"+file.exists());output=newFileOutputStream(file);bytebuffer[]=newbyte[4*1024];
while((inputStream.read(buffer))!=-1){output.write(buffer);}output.flush();}catch(FileNotFoundExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{try{output.close();}catch(IOExceptione){e.printStackTrace();}}returnfile;}
}
8.编写HttpDownLoader类packagecom.accp.util.file;importimportimportimportimportimportimportimportjava.io.BufferedReader;java.io.File;java.io.IOException;java.io.InputStream;java.io.InputStreamReader;java.net.HttpURLConnection;java.net.MalformedURLException;java.net.URL;
publicclassHttpDownLoader{privateURLurl;/***读取文本文件,返回字符串*@paramurlStr*@return*/
publicStringdownload(StringurlStr){StringBuffersb=newStringBuffer();Stringline=null;BufferedReaderbuffer=null;try{//创建一个url对象url=newURL(urlStr);//创建一个Http连接HttpURLConnectionurlcon=(HttpURLConnection)url.openConnection();//使用IO读取数据buffer=newBufferedReader(newInputStreamReader(urlcon.getInputStream()));//循环while((line=buffer.readLine())!=null){sb.append(line);}}catch(MalformedURLExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{try{buffer.close();}catch(IOExceptione){e.printStackTrace();}}returnsb.toString();}/***读取文件,并保存起来*@paramurlStr*@parampath*@paramfileName*@return-1:下载出错0:成功1:文件已经存在*/publicintdownFile(StringurlStr,Stringpath,StringfileName){
intresult=-1;InputStreaminputStream=null;FileUtilsfileUtils=newFileUtils();try{if(fileUtils.isFileExist(path+fileName)){return1;
}else{inputStream=getInputStreamFromUrl(urlStr);FileresultFile=fileUtils.write2SDFromInput(path,fileName,inputStream);if(resultFile==null){return-1;}}}catch(IOExceptione){e.printStackTrace();return-1;}finally{try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}}return0;}/***根据url地址获取输入流*@paramurlStr*@return*@throwsIOException*/publicInputStreamgetInputStreamFromUrl(StringurlStr)throwsIOException{url=newURL(urlStr);HttpURLConnectionurlCon=(HttpURLConnection)url.openConnection();InputStreaminputStream=urlCon.getInputStream();returninputStream;}}10.编写MainActivity类packagecom.accp.android;importcom.accp.util.file.HttpDownLoader;importimportimportimportimportandroid.app.Activity;android.os.Bundle;android.view.View;android.view.View.OnClickListener;android.widget.Button;
publicclassMainActivityextendsActivity{privateButtondownloadtxtbutton;privateButtondownloadmp3button;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);downloadtxtbutton=(Button)findViewById(R.id.downloadtxt);downloadmp3button=(Button)findViewById(R.id.downloadmp3);downloadtxtbutton.setOnClickListener(newDownloadtxtbuttonListener());downloadmp3button.setOnClickListener(newDownloadmp3buttonListener());}classDownloadtxtbuttonListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewarg0){HttpDownLoaderdl=newHttpDownLoader();Stringstr=dl.download("192.168.1.3:8081/downloadfile/android.txt");System.out.println(str);}}classDownloadmp3buttonListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewarg0){HttpDownLoaderhttpDownLoader=newHttpDownLoader();intresult=httpDownLoader.downFile("192.168.1.3:8081/downloadfile/android.txt","voa/","a.txt");System.out.println(result);}}}11.运行下载功能.12.检测: