Android(安卓)下载文件及写入SD卡
16lz
2021-12-04
引用:http://zhoujingxian.iteye.com/blog/859597
Android 下载文件及写入SD卡,实例代码
Main.xml代码- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <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>
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.learning.example"
- android:versionCode="1"
- android:versionName="1.0">
- <applicationandroid:icon="@drawable/icon"android:label="@string/app_name">
- <activityandroid:name=".Download"
- android:label="@string/app_name">
- <intent-filter>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- </application>
- <uses-sdkandroid:minSdkVersion="8"/>
- <!--访问网络和操作SD卡加入的两个权限配置-->
- <uses-permissionandroid:name="android.permission.INTERNET"/>
- <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- </manifest>
- packagecom.learning.example.util;
- 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.得到InputStream
- *4.从InputStream当中读取数据
- *@paramurlStr
- *@return
- */
- publicStringdownload(StringurlStr){
- StringBuffersb=newStringBuffer();
- Stringline=null;
- BufferedReaderbuffer=null;
- try{
- url=newURL(urlStr);
- HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();
- buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream()));
- while((line=buffer.readLine())!=null){
- sb.append(line);
- }
- }
- catch(Exceptione){
- e.printStackTrace();
- }
- finally{
- try{
- buffer.close();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- returnsb.toString();
- }
- /**
- *
- *@paramurlStr
- *@parampath
- *@paramfileName
- *@return
- *-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(IOExceptione){
- e.printStackTrace();
- }
- }
- return0;
- }
- /**
- *根据URL得到输入流
- *@paramurlStr
- *@return
- */
- publicInputStreamgetInputStreamFromURL(StringurlStr){
- HttpURLConnectionurlConn=null;
- InputStreaminputStream=null;
- try{
- url=newURL(urlStr);
- urlConn=(HttpURLConnection)url.openConnection();
- inputStream=urlConn.getInputStream();
- }catch(MalformedURLExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- returninputStream;
- }
- }
- packagecom.learning.example.util;
- importjava.io.File;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.io.OutputStream;
- importandroid.os.Environment;
- publicclassFileUtils{
- privateStringSDPATH;
- privateintFILESIZE=4*1024;
- publicStringgetSDPATH(){
- returnSDPATH;
- }
- publicFileUtils(){
- //得到当前外部存储设备的目录(/SDCARD)
- SDPATH= Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
- }
- /**
- *在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
- */
- publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminput){
- Filefile=null;
- OutputStreamoutput=null;
- try{
- createSDDir(path);
- file=createSDFile(path+fileName);
- output=newFileOutputStream(file);
- byte[]buffer=newbyte[FILESIZE];
- while((input.read(buffer))!=-1){
- output.write(buffer);
- }
- output.flush();
- }
- catch(Exceptione){
- e.printStackTrace();
- }
- finally{
- try{
- output.close();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- }
- returnfile;
- }
- }
- packagecom.learning.example;
- importcom.learning.example.util.HttpDownloader;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- publicclassDownloadextendsActivity{
- privateButtondownlaodTxtButton;
- privateButtondownlaodMP3Button;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- downlaodTxtButton=(Button)findViewById(R.id.downloadTxt);
- downlaodTxtButton.setOnClickListener(newDownloadTxtListener());
- downlaodMP3Button=(Button)findViewById(R.id.downloadMp3);
- downlaodMP3Button.setOnClickListener(newDownloadMP3Listener());
- }
- classDownloadTxtListenerimplementsOnClickListener{
- @Override
- publicvoidonClick(Viewv){
- HttpDownloaderdownloader=newHttpDownloader();
- Stringlrc=downloader.download("http://172.16.11.9:8080/test/1.lrc");
- System.out.println(lrc);
- }
- }
- classDownloadMP3ListenerimplementsOnClickListener{
- @Override
- publicvoidonClick(Viewv){
- HttpDownloaderdownloader=newHttpDownloader();
- intresult=downloader.downFile("http://172.16.11.9:8080/test/1.mp3","voa/","1.map3");
- System.out.println(result);
- }
- }
- }
Notice:访问网络和操作SD卡 记得加入的两个权限配置
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
更多相关文章
- NPM 和webpack 的基础使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
- Android的断点设置
- 使用Scala开发Android
- Android桌面小部件实例 桌面小时钟
- Android(安卓)从代码中打开淘宝和亚马逊、facebook、Message
- Creating a ContextMenu on a ListView
- Android(安卓)Google Maps API key 申请
- android弹出对话框大全