Android下载文件到SD卡

1、 获取一个URL

URL url = new URL(“192.168.1.1:8080/files/01.doc”);

2、 使用URL打开一个HttpURLConnection

HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

public abstract class HttpURLConnection extends URLConnection

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

3、 获取InputStream

InputStream inputStream = urlConn.getInputStream();

4、 然后按照正常的输出流写入到SD卡中就可以了

//获取SD卡的路径
String SDPath = Environment.getExternalStorageDirectory() + “/“;
//创建要使用的文件夹
File dir = new File(SDPath + dirName);
dir.mkdirs();
//创建输出文件
File file = new File(SDPath + dirName + fileName);
file.createNewFile();
output = new FileOutputStream(file);
byte buffer [] = new byte[1 * 1024];
while((inputStream.read(buffer)) != -1){
output.write(buffer);
}
output.flush();

public class Environment extends Object java.lang.Object ↳ android.os.Environment

5、 还必须做的就是在AndroidManifest.xml文件中设置访问网络和写SD卡的权限:

(特别说明:本文部分内容是在观看marschen的Android视频教程时做的笔记,感谢marschen推出的视频教程,这里也推荐给大家:http://www.marschen.com/portal.php)

arthinking wechat
欢迎关注itzhai公众号