下载网络图片到本地文件中
1.首先要判断手机中是否有SD卡
String status=Environment.getExternalStorageState();
if(status.equals(Environment.MEDIA_MOUNTED)){
return true;
}else{
return false;
}
2.得到手机内存设备或者SD卡的根目录
private String getRootLocation(){
if(checkSD()){
return Environment.getExternalStorageDirectory().getPath();
}else{
return Environment.getDownloadCacheDirectory().getPath();
}
}
3.创建文件夹存储文件
String package="/yuetu/picture"开头一定要带"/";
File imgfile=new File(getRootLocation+package);
if(!file.exists){
file.mkdirs();
}
4.创建文件存储文件
String mImgPath="/yuetu/picture/11.jpg"
File file=new File(getRootLocation+mImgPath);
5.从网络获取字节流
public byte[] readImage(String path) throws Exception {
URL url = new URL(path);
// 记住使用的是HttpURLConnection类
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 如果运行超过5秒会自动失效 这是android规定
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
// 调用readStream方法
return readStream(inStream);
}
6.创建文件流读取字节留
byte[] imgdata=readImage(mImg);
FileOutputStream outStream = new FileOutputStream(imgfile);
outStream.write(imgdata);
7.关闭流文件
outStream.close();