android 下载文件

来源:互联网 发布:php 截取第一个字符串 编辑:程序博客网 时间:2024/06/05 00:11
    /**
     * 下载文件
     *
     * @param urlpath
     *            下载路径
     * @param savePath
     *            保存路径
     * @throws FileNotFoundException
     * @throws IOException
     * @throws InterruptedException
     */
    public static void downloadFile(String urlpath, String savePath)
            throws FileNotFoundException, IOException, InterruptedException {
        // 将字符串形式的path,转换成一个url
        InputStream inStream = null;
        FileOutputStream fos = null;
        char[] ch = urlpath.toCharArray();  
         for (int i = 0; i < ch.length; i++) {
             char c = ch[i];  
             if (isChinese(c)) {
                 String string =java.net.URLEncoder.encode(String.valueOf(ch[i]),"UTF-8");
                 urlpath = urlpath.replaceAll(String.valueOf(c), string);
            }
         }
        
        URL url = new URL(urlpath);

        // 得到url之后,将要开始连接网络。
        // 首先,实例化一个HTTP连接对象conn
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 定义请求方式为GET。
        conn.setRequestMethod("GET");
        // 定义请求时间,在ANDROID中最好是不好超过10秒。否则将被系统回收。
        conn.setConnectTimeout(5 * 1000);
        if (conn.getResponseCode() == 200) {
            File file = new File(savePath);
            file.getParentFile().mkdirs();
            file.delete();
            file.createNewFile();
            fos = new FileOutputStream(file);
            // 返回码为真
            // 从服务器传递过来数据,是一个输入的动作。定义一个输入流,获取从服务器返回的数据
            inStream = conn.getInputStream();
            byte[] buffer = new byte[50 * 1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                Thread.sleep(200);
            }
        }
        inStream.close();
        fos.close();

    }


 private static final boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
            return true;  
        }  
        return false;  
    }

原创粉丝点击