• Android 经验之文件下载


    在Android 开发中,我们肯定会接触到下载需求,那么如何通过技术实现呢?

    一、简单实现:

    通过了解HTTP原理,我们应该可以知道,HTTP学习的时候,可以通过HTTPGET方式来进行文件下载:

    new Thread(new Runnable() {
    
        @Override
        public void run() {
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            // 如果不是,就加尾缀
            if (!fileName.endsWith(MimeUtils.guessExtensionFromMimeType(mimetype))) {
                fileName = fileName + "." + MimeUtils.guessExtensionFromMimeType(mimetype);
            }
            // 限制文件名的长度
            if (fileName.length() > 50) {
                fileName = fileName.substring(fileName.length() - 50);
            }
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
            HttpConnectionParams.setSoTimeout(params, 5 * 1000);
            HttpGet httpGet = new HttpGet(url);
            try {
                File file = new File(Environment.getExternalStorageDirectory(), fileName);
                if (!file.exists()) {
                    file.createNewFile();
                } else {
                    boolean flag = file.delete();
                    if (flag) {
                        file.createNewFile();
                    } else {
                        // 目前设定是: 如果删除失败,就不进行下载了 
                return; } } RandomAccessFile randomFile = new RandomAccessFile(file, "rw"); HttpResponse response = new DefaultHttpClient(params).execute(httpGet); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); randomFile.seek(randomFile.length()); byte[] buffer = new byte[1024]; int lenght = 0; while ((lenght = in.read(buffer)) > 0) { randomFile.write(buffer, 0, lenght); if (randomFile.length() == contentLength) { // 下载完成 } } randomFile.close(); httpGet.abort(); } catch (Exception e) { e.printStackTrace(); } } }).start();
  • 相关阅读:
    Windows系统环境变量path优先级测试报告
    URI和URL的区别
    智能引导式报错(Class file name must end with .class)
    【Algorithm】冒泡排序
    【C语言】练习2-9
    【C语言】练习2-8
    【C语言】练习2-1
    【C语言】练习1-23
    【C语言】练习1-22
    【C语言】练习1-21
  • 原文地址:https://www.cnblogs.com/renhui/p/6382581.html
Copyright © 2020-2023  润新知