使用HTTP协议下载文件
- 创建一个URL对象
- 通过URL对象,创建一个HttpURLConnection对象
- 调用getInputStream()方法得到InputStream对象
- 从InputStream对象中读取数据
1 InputStream inputStream = null; 2 try { 3 URL url = new URL(urlstr); 4 HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); 5 in = urlConn.getInputStream(); 6 } catch (MalformedURLException e) { 7 e.printStackTrace(); 8 } catch (IOException e) { 9 e.printStackTrace(); 10 }
向SD卡中写入数据
- 通过Environment.getExternalStorageDirectory()获取存放路径
- 创建一个outputStream对象,文件路径以参数传入
- 将InputStream对象中读取的内容写入文件
1 File file = new File(Environment.getExternalStorageDirectory(), filename); 2 OutputStream out=null; 3 try { 4 out=new FileOutputStream(file); 5 byte[] buffer=new byte[4*1024]; 6 while(in.read(buffer)!=-1) { 7 out.write(buffer); 8 } 9 out.flush(); 10 } catch (FileNotFoundException e) { 11 e.printStackTrace(); 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } finally { 15 try { 16 out.close(); 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 }
权限添加
1 <!-- 访问网络权限 --> 2 <uses-permission android:name="android.permission.INTERNET" 3 <!-- 在SDCard中创建于删除文件的权限 --> 4 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> 5 <!-- 往SDCard中写入数据的权限 --> 6 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>