Android从远程服务器下载文件到本地sd卡中

来源:互联网 发布:miss的淘宝店网址 编辑:程序博客网 时间:2024/05/17 22:04

实现Android从远程服务器下载文件到本地sd卡中。

 

File file = new File(newFilename);//如果目标文件已经存在,则删除。产生覆盖旧文件的效果if(file.exists()){    file.delete();}try {         // 构造URL           URL url = new URL(_urlStr);            // 打开连接            URLConnection con = url.openConnection();         //获得文件的长度         int contentLength = con.getContentLength();         System.out.println("长度 :"+contentLength);         // 输入流            InputStream is = con.getInputStream();           // 1K的数据缓冲            byte[] bs = new byte[1024];            // 读取到的数据长度            int len;            // 输出的文件流            OutputStream os = new FileOutputStream(newFilename);            // 开始读取            while ((len = is.read(bs)) != -1) {                os.write(bs, 0, len);            }           // 完毕,关闭所有链接            os.close();           is.close();            } catch (Exception e) {        e.printStackTrace();}


 

1 0
原创粉丝点击