Android 不解压直接读取zip包的方法
之前项目中遇到个需求,总监让我们把从服务器下载下来的资源不解压直接读取里面的资源,这样的话就省去了一个个校验资源是否正确的步骤,听着貌似有点道理。。。废话不多说直接上代码。
目前我所试验过的可以读取的资源有文本、图片、xml文件。
文本:
zip包目录结构:res/txt/data.json
文件sd卡路径:android.os.Environment.getExternalStorageDirectory()+“/res.zip”
publicstaticStringreadDataFile(Stringfile)throwsException{
//截取路径的文件名res
StringfileName=file.substring(file.length()-9,file.length()-4);
ZipFilezf=newZipFile(file);
InputStreamin=newBufferedInputStream(newFileInputStream(file));
ZipInputStreamzin=newZipInputStream(in);
ZipEntryze;
while((ze=zin.getNextEntry())!=null){
if(ze.isDirectory()){
//Donothing
}else{
if(ze.getName().equals(fileName+"/txt/data.json")){
BufferedReaderbr=newBufferedReader(
newInputStreamReader(zf.getInputStream(ze)));
Stringline;
while((line=br.readLine())!=null){
returnline;
}
br.close();
}
}
}
zin.closeEntry();
return"";
}
上面方法比较简单没什么好说的,大家理解就行,有点需要注意的就是在判断是否是想要读取的文件的时候,这里的路径是以zip的压缩目录为根目录做比较。也就是if(ze.getName().equals(fileName+"/txt/data.json"))这句话中的fileName当前值为res。最后返回读取的内容String就完事了。
图片和xml文件的读取都差不多,下面直接贴出代码了。
图片:
zip包目录结构:res/pic/haha.png
文件sd卡路径:android.os.Environment.getExternalStorageDirectory()+“/res.zip”
publicstaticBitmapreadGuidePic(Stringfile,StringResId)throwsException{
StringfileName=file.substring(file.length()-9,file.length()-4);
ZipFilezf=newZipFile(file);
InputStreamin=newBufferedInputStream(newFileInputStream(file));
ZipInputStreamzin=newZipInputStream(in);
ZipEntryze;
while((ze=zin.getNextEntry())!=null){
if(ze.isDirectory()){
//Donothing
}else{
Log.i("tag","file-"+ze.getName()+":"+ze.getSize()+"bytes");
if(ze.getName().equals(fileName+"/pic/haha.png")){
InputStreamis=zf.getInputStream(ze);
Bitmapbitmap=BitmapFactory.decodeStream(is);
returnbitmap;
}
}
}
zin.closeEntry();
returnnull;
}
xml文件:
zip包目录结构:res/xml/app.xml
文件sd卡路径:android.os.Environment.getExternalStorageDirectory()+“/res.zip”
publicstaticInputStreamreadAppFile(Stringfile)throwsIOException{
StringfileName=file.substring(file.length()-9,file.length()-4);
ZipFilezf=newZipFile(file);
InputStreamin=newBufferedInputStream(newFileInputStream(file));
ZipInputStreamzin=newZipInputStream(in);
ZipEntryze;
while((ze=zin.getNextEntry())!=null){
if(ze.isDirectory()){
//Donothing
}else{
if(ze.getName().equals(fileName+"/xml/app.xml")){
InputStreaminputStream=zf.getInputStream(ze);
returninputStream;
}
}
}
zin.closeEntry();
returnnull;
}
以上这篇Android不解压直接读取zip包的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。