Rumah > Soal Jawab > teks badan
天蓬老师2017-04-17 17:46:08
1.创建存放图片的文件夹
2.创建存储图片文件
3.下载图片写入文件
//一般图片存储在手机SD卡 获取手机的SD卡根目录增加temp的文件夹路径
Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp";
下载图片并存储在本地主要代码
void doSaveImage(){
String filePath = FileUtil.getEnvironmentPath();
Log.i("doSaveImage",filePath + "");
File fileFloder = new File(filePath);
if(!fileFloder.exists()){
if(fileFloder.mkdirs()){
Log.i("doSaveImage","file.mkdirs" + " true");
}else{
Log.i("doSaveImage","file.mkdirs" + " false");
Toast.makeText(this,"save error!",Toast.LENGTH_SHORT).show();
}
}
InputStream in = null;
OutputStream out = null;
try {
Log.i("doSaveImage",AppConst.IMG_HEAD_URL + mUrl);
URL url = new URL(AppConst.IMG_HEAD_URL + mUrl);
URLConnection con = url.openConnection();
con.setConnectTimeout(5*1000);
int contentLength = con.getContentLength();
in = con.getInputStream();
byte[] bytes = new byte[1024];
File file = new File(fileFloder.getPath(), name +".jpg");
out = new FileOutputStream(file);
int len;
while ((len = in.read(bytes)) != -1){
Log.i("doSaveImage",len + "");
out.write(bytes,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try{
if(in != null) in.close();
if(out != null) out.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
PHP中文网2017-04-17 17:46:08
String path = null;
if (getExternalCacheDir() != null) {//判断外部存储是否可用,也就是SD卡
//假如有就用SD卡
path = context.getExternalCacheDir().getAbsolutePath() + File.separator;
} else {
//否则存在手机自带内存
path= context.getCacheDir().getAbsolutePath() + File.separator;
}
以上都只是写到了根目录,可以自行根据需求再新建目录
getExternalCacheDir方法context可以直接用Application的,或者直接在Application里面调用getExternalCacheDir