博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android HTTP下载文件并保存到本地或SD卡
阅读量:4970 次
发布时间:2019-06-12

本文共 6678 字,大约阅读时间需要 22 分钟。

想把文件保存到SD卡中,一定要知道SD卡的路径,获取SD卡路径:

Environment.getExternalStorageDirectory()

另外,在保存之前要判断SD卡是否已经安装好,并且可读写:

//判断SDcard是否存在并且可读写if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                    service.saveToSDCard(filename,filecontent);                    Toast.makeText(getApplicationContext(), R.string.success, 1).show();                }else{                    Toast.makeText(getApplicationContext(), R.string.sdcarderror, 1).show();                }

实例

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

 2.代码编写

AndroidMainfest.xml中配置

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

package util;import android.util.Log;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.URL;/** * Created by Spring on 2015/11/7. * 下载工具类 */public class HttpDownloader {    private URL url = null;    private final String TAG = "TAG";    /**     * 读取文本文件     * @param urlStr url路径     * @return 文本信息     * 根据url下载文件,前提是这个文件中的内容是文本,     * 1.创建一个URL对象     * 2.通过URL对象,创建一个Http连接     * 3.得到InputStream     * 4.从InputStream中得到数据     */    public String download(String urlStr) {        StringBuffer sb = new StringBuffer();        String line = null;        BufferedReader bufferedReader = null;        try {            url = new URL(urlStr);            //创建http连接            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();            //使用IO流读取数据            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));            while ((line = bufferedReader.readLine()) != null) {                sb.append(line);            }        } catch (IOException e) {            e.printStackTrace();        }        finally {            try {                bufferedReader.close();            } catch (IOException e) {                e.printStackTrace();            }        }        Log.e("TAG","下载txt文件");        Log.e("TAG",sb.toString());        return sb.toString();    }    /**     * 读取任何文件     * 返回-1 ,代表下载失败。返回0,代表成功。返回1代表文件已经存在     *     * @param urlStr     * @param path     * @param fileName     * @return     */    public int downlaodFile(String urlStr, String path, String fileName) {        InputStream input = null;        try {            FileUtil fileUtil = new FileUtil();            if (fileUtil.isFileExist(path + fileName)) {                return 1;            } else {                input = getInputStearmFormUrl(urlStr);                File resultFile = fileUtil.write2SDFromInput(path,fileName,input);                if (resultFile == null)                    return -1;            }        } catch (IOException e) {            e.printStackTrace();            return -1;        }        finally {            try {                input.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return  0;    }    public InputStream getInputStearmFormUrl(String urlStr) throws IOException {        url = new URL(urlStr);        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();        InputStream input = urlConn.getInputStream();        return input;    }}

FileUtil.java

package util;import android.os.Environment;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;/** * Created by Spring on 2015/11/7. */public class FileUtil {    private String SDPATH;    public FileUtil() {    }    public String getSDPATH() {        return SDPATH;    }    public FileUtil(String SDPATH){        //得到外部存储设备的目录(/SDCARD)        SDPATH = Environment.getExternalStorageDirectory() + "/" ;    }    /**     * 在SD卡上创建文件     * @param fileName     * @return     * @throws java.io.IOException     */    public File createSDFile(String fileName) throws IOException {        File file = new File(SDPATH + fileName);        file.createNewFile();        return file;    }    /**     * 在SD卡上创建目录     * @param dirName 目录名字     * @return 文件目录     */    public File createDir(String dirName){        File dir = new File(SDPATH + dirName);        dir.mkdir();        return dir;    }    /**     * 判断文件是否存在     * @param fileName     * @return     */    public boolean isFileExist(String fileName){        File file = new File(SDPATH + fileName);        return file.exists();    }    public File write2SDFromInput(String path,String fileName,InputStream input){        File file = null;        OutputStream output = null;        try {            createDir(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 (IOException e) {            e.printStackTrace();        }        finally {            try {                output.close();            } catch (IOException e) {                e.printStackTrace();            }        }        return file;    }}

3.MainActivity

package com.jingling.practice.downloadtest;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;import util.HttpDownloader;public class MainActivity extends Activity {    HttpDownloader downloader ;    private Button btn_downFile;    private Button btn_downMP3;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn_downFile = (Button)this.findViewById(R.id.button);        btn_downMP3 = (Button)this.findViewById(R.id.button2);        btn_downFile.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                downloader = new HttpDownloader();                String urlStr = "http://172.17.54.91:8080/download/down.txt";                downloader.download(urlStr);            }        });        btn_downMP3.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                String urlStr="http://172.17.54.91:8080/download/1.mp3";                String path="file";                String fileName="2.mp3";                HttpDownloader httpDownloader = new HttpDownloader();                httpDownloader.downlaodFile(urlStr,path,fileName);            }        });    }}

 

转载于:https://www.cnblogs.com/zhujiabin/p/7724207.html

你可能感兴趣的文章
35.大质数
查看>>
spring包说明
查看>>
从技术到管理:工作转型后角色定位
查看>>
linux快速查找文件
查看>>
【bzoj4008】 HNOI2015—亚瑟王
查看>>
lambda、map、reduce、filter函数讲解
查看>>
Apache下通过shell脚本提交网站404死链
查看>>
java ftp下载文件
查看>>
hint使用
查看>>
FLEX 通过url 得到网页内容 xml通信
查看>>
打包压缩
查看>>
PASCAL语言子集的词法、语法分析器之实现
查看>>
通用FTP Client模块设计与实现
查看>>
【javascript笔记】声明函数的三种方式
查看>>
嵌入式软件工程师C语言经典笔试2
查看>>
DPlot.v2.3.4.4 1CD DPlot适用于科学研究,工程技术的图表软件。用来显示2维,3维数据。...
查看>>
Django 中间件
查看>>
IFrame 框架的用法简介
查看>>
单词扭转,字符逆转
查看>>
RESTful规范
查看>>