您的位置:首页 > 移动开发 > Android开发

android studio 读取assets中zip文件

2016-01-16 17:50 453 查看
今天做一个从assets获取zip压缩包中的图片,显示在recyclerview中但怎么获取都获取不到

后来想起 eclipse 与android studio 中项目的结构是不一样的,assets不能直接建在项目下

应建立在src >> main >>assets

解读feng.zip 压缩包中的图片,你可以直接保存到sd卡中,也可以直接简单保存在list集合中

1:直接保存在list集合中的一种方法

List<Bitmap> btms = new ArrayList<>();
public void unzip(String assestsname){
btms.clear();
try {
InputStream open = getResources().getAssets().open(assestsname);
ZipInputStream zipinputstream = new ZipInputStream(open);
ZipEntry nextEntry = zipinputstream.getNextEntry();
while(nextEntry != null){

if(!nextEntry.isDirectory()){//判断不是文件
if(nextEntry.getName().contains(".jpg")){//我这里里是jpg格式图片所以简单操作
Bitmap bitmap = BitmapFactory.decodeStream(zipinputstream);
btms.add(bitmap);
}
}
nextEntry = zipinputstream.getNextEntry();
}
Log.i("test","===什么长度=="+btms.size());
zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}


2:解读之后保存到sd中,然后你可以从sd卡直接获取图片的一种方式

try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
AssetManager assets = getResources().getAssets();

//String[] list = assets.list("header/");
unZip("header/feng.zip", path); }else{ Log.i("test","没有没有sd卡"); } } catch (Exception e) { e.printStackTrace(); }

*/
public  void unZip( String assetName, String savefilename) throws IOException {
// 创建解压目标目录
File file = new File(savefilename);
// 如果目标目录不存在,则创建
if (!file.exists()) {
file.mkdirs();
}

InputStream inputStream = getAssets().open(assetName);
//      inputStream =getClass().getResourceAsStream(assetName;//也可以进行流解读
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
// 读取一个进入点
ZipEntry nextEntry = zipInputStream.getNextEntry();
byte[] buffer = new byte[1024 * 1024];
int count = 0;
// 如果进入点为空说明已经遍历完所有压缩包中文件和目录
while (nextEntry != null) {
// 如果是一个文件夹
if (nextEntry.isDirectory()) {
file = new File(savefilename + File.separator + nextEntry.getName());
if (  !file.exists()) {
file.mkdir();
}
} else {
// 如果是文件那就保存
file = new File(savefilename + File.separator + nextEntry.getName());
// 则解压文件
if ( !file.exists()) {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
while ((count = zipInputStream.read(buffer)) != -1) {
fos.write(buffer, 0, count);
}

fos.close();
}
}

//这里很关键循环解读下一个文件
nextEntry = zipInputStream.getNextEntry();
}
zipInputStream.close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: