android - 页面显示andriod系统目录下图片

浏览:33日期:2022-11-27

问题描述

从服务器下载图片到本地路径,然后在前端展示那个图片,路径这块应该怎么处理?求大神支招啊。

问题解答

回答1:

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(); }} }回答2:

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

相关文章: