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

实现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();
}


 

posted @ 2014-04-02 20:33  Tom19971220  阅读(2)  评论(0编辑  收藏  举报  来源
个人网站