Android学习笔记-文件下载
工具类FileUtils.java
packagecom.example.filedownload_01;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importandroid.os.Environment;publicclassFileUtils{privateStringSDPATH;publicStringgetSDPATH(){returnSDPATH;}publicFileUtils(){//得到当前外部存储设备的目录一般是/sdcardSDPATH=Environment.getExternalStorageDirectory()+"/";}/***在SD卡上创建文件*@paramfileName文件名*@return新创建的文件*@throwsIOException*/publicFilecreateSDFile(StringfileName)throwsIOException{Filefile=newFile(SDPATH+fileName);file.createNewFile();returnfile;}/***在SD卡上创建目录*@paramdirName目录名*@return*/publicFilecreateSDDir(StringdirName){Filedir=newFile(SDPATH+dirName);dir.mkdir();returndir;}/***判断SD卡上是否存在文件*@paramfileName*@return*/publicbooleanisFileExist(StringfileName){Filefile=newFile(SDPATH+fileName);returnfile.exists();}/***将一个InputStream里面的数据写入到SD卡中*@parampath路径*@paramfileName文件名*@paraminput输入流*@return写入SD卡的文件*/publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminput){Filefile=null;OutputStreamoutput=null;try{createSDDir(path);file=createSDFile(path+fileName);output=newFileOutputStream(file);bytebuffer[]=newbyte[4*1024];while((input.read(buffer))!=-1){output.write(buffer);}output.flush();}catch(Exceptione){e.printStackTrace();}finally{try{output.close();}catch(Exceptione2){e2.printStackTrace();}}returnfile;}}
HttpDownloader.java
packagecom.example.filedownload_01;importjava.io.BufferedReader;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importorg.apache.http.message.BufferedHeader;publicclassHttpDownloader{privateURLurl=null;publicStringdownload(StringurlStr){StringBuffersb=newStringBuffer();Stringline=null;BufferedReaderbuffer=null;try{url=newURL(urlStr);HttpURLConnectionurlConnection=(HttpURLConnection)url.openConnection();buffer=newBufferedReader(newInputStreamReader(urlConnection.getInputStream()));while((line=buffer.readLine())!=null){sb.append(line);}}catch(Exceptione){e.printStackTrace();}finally{try{buffer.close();}catch(Exceptione2){e2.printStackTrace();}}returnsb.toString();}/***@paramurlStr*url*@parampath*保存路径*@paramfileName*文件名*@return返回值-1:表示下载文件出错,0表示下载文件成功,1表示文件已经存在*/publicintdownloadFile(StringurlStr,Stringpath,StringfileName){InputStreaminputStream=null;try{FileUtilsfileUtils=newFileUtils();if(fileUtils.isFileExist(path+fileName)){return1;//文件已经存在}else{inputStream=getInputStreamFromUrl(urlStr);FileresultFile=fileUtils.write2SDFromInput(path,fileName,inputStream);if(resultFile==null){return-1;}}}catch(Exceptione){e.printStackTrace();return-1;}finally{try{inputStream.close();}catch(Exceptione){e.printStackTrace();}}return0;}publicInputStreamgetInputStreamFromUrl(StringurlStr)throwsIOException{url=newURL(urlStr);HttpURLConnectionurlConnection=(HttpURLConnection)url.openConnection();InputStreaminputStream=urlConnection.getInputStream();returninputStream;}}
MainActivity.java
packagecom.example.filedownload_01;importandroid.support.v7.app.ActionBarActivity;importandroid.R.integer;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.HandlerThread;importandroid.os.Looper;importandroid.os.Message;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.Toast;publicclassMainActivityextendsActionBarActivity{privateButtondownloadTxtButton=null;privateButtondownloadMp3Button=null;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);downloadMp3Button=(Button)findViewById(R.id.downloadMp3Button);downloadTxtButton=(Button)findViewById(R.id.downloadTxtButton);downloadTxtButton.setOnClickListener(newDownloadTextListener());downloadMp3Button.setOnClickListener(newDownloadMp3Listener());}classDownloadTextListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewv){System.out.println("下载TXT文件");Toast.makeText(MainActivity.this,"开始下载TXT",Toast.LENGTH_SHORT).show();StringurlStr="http://www.51voa.com/lrc/201411/se-health-surgical-safari-cosmetic-18nov14.lrc";Stringpath="umgsai_download/";StringfileName="test.lrc";//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能HandlerThreadhandlerThread=newHandlerThread("handler_Thread");handlerThread.start();MyHandlermyHandler=newMyHandler(handlerThread.getLooper());Messagemsg=myHandler.obtainMessage();//msg.obj="abc";//简单数据Bundlebundle=newBundle();bundle.putString("urlStr",urlStr);bundle.putString("fileName",fileName);bundle.putString("path",path);msg.setData(bundle);//将msg发送到目标对象,即生成msg对象的Handler对象msg.sendToTarget();//HttpDownloaderhttpDownloader=newHttpDownloader();//Stringlrc=httpDownloader.download("http://localhost/menu/log.txt");//System.out.println(lrc);}}classDownloadMp3ListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewv){//HttpDownloaderhttpDownloader=newHttpDownloader();//intresult=httpDownloader.downloadFile("","voa/","test.mp3");//System.out.println(result);Toast.makeText(MainActivity.this,"开始下载MP3",Toast.LENGTH_SHORT).show();StringurlStr="http://127.0.0.1/menu/test.apk";Stringpath="umgsai_download/";StringfileName="test.apk";//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能HandlerThreadhandlerThread=newHandlerThread("handler_Thread");handlerThread.start();MyHandlermyHandler=newMyHandler(handlerThread.getLooper());Messagemsg=myHandler.obtainMessage();//msg.obj="abc";//简单数据Bundlebundle=newBundle();bundle.putString("urlStr",urlStr);bundle.putString("fileName",fileName);bundle.putString("path",path);msg.setData(bundle);//将msg发送到目标对象,即生成msg对象的Handler对象msg.sendToTarget();}}classMyHandlerextendsHandler{publicMyHandler(){}publicMyHandler(Looperlooper){super(looper);}@OverridepublicvoidhandleMessage(Messagemsg){super.handleMessage(msg);Bundlebundle=msg.getData();StringurlStr=bundle.getString("urlStr");StringfileName=bundle.getString("fileName");Stringpath=bundle.getString("path");HttpDownloaderhttpDownloader=newHttpDownloader();intresult=httpDownloader.downloadFile(urlStr,path,fileName);System.out.println(result);Toast.makeText(MainActivity.this,"~~",Toast.LENGTH_SHORT).show();//Stringlrc=httpDownloader.download(fileName);//System.out.println(lrc);}}}
下载文件的任务不能放在主线程里面,否则会抛异常。
下载MP3文件时会存在问题,暂未解决。
把上面的代码重新整理了一份
FileUtils.java
packagecom.example.utils;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importandroid.os.Environment;publicclassFileUtils{privateStringSDPATH;publicStringgetSDPATH(){returnSDPATH;}publicFileUtils(){//得到当前外部存储设备的目录///SDCARDSDPATH=Environment.getExternalStorageDirectory()+"/";}/***在SD卡上创建文件**@throwsIOException*/publicFilecreatSDFile(StringfileName)throwsIOException{Filefile=newFile(SDPATH+fileName);file.createNewFile();returnfile;}/***在SD卡上创建目录**@paramdirName*/publicFilecreatSDDir(StringdirName){Filedir=newFile(SDPATH+dirName);dir.mkdir();returndir;}/***判断SD卡上的文件夹是否存在*/publicbooleanisFileExist(StringfileName){Filefile=newFile(SDPATH+fileName);returnfile.exists();}/***将一个InputStream里面的数据写入到SD卡中*/publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminput){Filefile=null;OutputStreamoutput=null;try{creatSDDir(path);file=creatSDFile(path+fileName);output=newFileOutputStream(file);bytebuffer[]=newbyte[4*1024];while((input.read(buffer))!=-1){output.write(buffer);}output.flush();}catch(Exceptione){e.printStackTrace();}finally{try{output.close();}catch(Exceptione){e.printStackTrace();}}returnfile;}}
HttpDownloader.java
packagecom.example.utils;importjava.io.BufferedReader;importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;publicclassHttpDownloader{privateURLurl=null;/***根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容*1.创建一个URL对象*2.通过URL对象,创建一个HttpURLConnection对象*3.得到InputStram*4.从InputStream当中读取数据*@paramurlStr*@return*/publicStringdownload(StringurlStr){StringBuffersb=newStringBuffer();Stringline=null;BufferedReaderbuffer=null;try{//创建一个URL对象url=newURL(urlStr);//创建一个Http连接HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();//使用IO流读取数据buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream()));while((line=buffer.readLine())!=null){sb.append(line);}}catch(Exceptione){e.printStackTrace();}finally{try{buffer.close();}catch(Exceptione){e.printStackTrace();}}returnsb.toString();}/***该函数返回×××-1:代表下载文件出错0:代表下载文件成功1:代表文件已经存在*/publicintdownFile(StringurlStr,Stringpath,StringfileName){InputStreaminputStream=null;try{FileUtilsfileUtils=newFileUtils();if(fileUtils.isFileExist(path+fileName)){return1;}else{inputStream=getInputStreamFromUrl(urlStr);FileresultFile=fileUtils.write2SDFromInput(path,fileName,inputStream);if(resultFile==null){return-1;}}}catch(Exceptione){e.printStackTrace();return-1;}finally{try{inputStream.close();}catch(Exceptione){e.printStackTrace();}}return0;}/***根据URL得到输入流**@paramurlStr*@return*@throwsMalformedURLException*@throwsIOException*/publicInputStreamgetInputStreamFromUrl(StringurlStr)throwsMalformedURLException,IOException{url=newURL(urlStr);HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();InputStreaminputStream=urlConn.getInputStream();returninputStream;}}
下载不能在主线程里进行
classMp3ButtonListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewv){//TODOAuto-generatedmethodstubStringurlStr="http://192.168.77.215/jstree/snowdreams.mp3";Stringpath="umgsai_download/";StringfileName="snowdreams.mp3";//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能HandlerThreadhandlerThread=newHandlerThread("handler_Thread");handlerThread.start();Mp3Handlermp3Handler=newMp3Handler(handlerThread.getLooper());Messagemsg=mp3Handler.obtainMessage();Bundlebundle=newBundle();bundle.putString("urlStr",urlStr);bundle.putString("fileName",fileName);bundle.putString("path",path);msg.setData(bundle);//将msg发送到目标对象,即生成msg对象的Handler对象msg.sendToTarget();}}classMp3HandlerextendsHandler{publicMp3Handler(){}publicMp3Handler(Looperlooper){super(looper);}@OverridepublicvoidhandleMessage(Messagemsg){//TODOAuto-generatedmethodstubsuper.handleMessage(msg);Bundlebundle=msg.getData();StringurlStr=bundle.getString("urlStr");StringfileName=bundle.getString("fileName");Stringpath=bundle.getString("path");HttpDownloaderhttpDownloader=newHttpDownloader();intresult=httpDownloader.downFile(urlStr,path,fileName);System.err.println(result);Toast.makeText(MainActivity.this,result+"~~",Toast.LENGTH_SHORT).show();}}
需要连接网络和向外部存储设备写数据的权限
<uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在模拟器上测试正常,但是在真机上测试出问题。暂未解决。开发中建议使用这里的代码。第一次整理的代码可能存在问题,未测试。
读取网络文件内容如下
classParseButtonListenerimplementsOnClickListener{@OverridepublicvoidonClick(Viewv){StringurlStr="http://192.168.77.215/jstree/test.xml";Stringpath="umgsai_download/";StringfileName="test.lrc";//生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能HandlerThreadhandlerThread=newHandlerThread("handler_Thread");handlerThread.start();MyHandlermyHandler=newMyHandler(handlerThread.getLooper());Messagemsg=myHandler.obtainMessage();//msg.obj="abc";//简单数据Bundlebundle=newBundle();bundle.putString("urlStr",urlStr);bundle.putString("fileName",fileName);bundle.putString("path",path);msg.setData(bundle);//将msg发送到目标对象,即生成msg对象的Handler对象msg.sendToTarget();}
classMyHandlerextendsHandler{publicMyHandler(){}publicMyHandler(Looperlooper){super(looper);}@OverridepublicvoidhandleMessage(Messagemsg){super.handleMessage(msg);Bundlebundle=msg.getData();StringurlStr=bundle.getString("urlStr");StringfileName=bundle.getString("fileName");Stringpath=bundle.getString("path");HttpDownloaderhttpDownloader=newHttpDownloader();Stringresult=httpDownloader.download(urlStr);System.err.println(result);Toast.makeText(MainActivity.this,"~~",Toast.LENGTH_SHORT).show();//Stringlrc=httpDownloader.download(fileName);//System.out.println(lrc);}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。