您的位置:首页 > 其它

解压assets中的zip压缩文件到指定目录

2013-11-03 22:12 453 查看
解压函数:
/**
* 解压assert中的文件到指定目录
* @param is	文件输入流
* @param dir	目标路径(路径已存在)
* @throws IOException
*/
private void unzip (InputStream is, String dir) throws IOException
{
File dest = new File(dir);
if ( !dest.isDirectory())
throw new IOException("Invalid Unzip destination " + dest);

if(null == is){
throw new IOException("InputStream is null");
}

ZipInputStream zip = new ZipInputStream(is);

ZipEntry ze;

while ( (ze = zip.getNextEntry()) != null ) {
final String path = dest.getAbsolutePath()
+ File.separator + ze.getName();

// Create any entry folders
String zeName = ze.getName();
char cTail = zeName.charAt(zeName.length() - 1);
if ( cTail == File.separatorChar)
{
File file = new File(path);
if(!file.exists()){
if ( !file.mkdirs() ){
throw new IOException("Unable to create folder " + file);
}
}
continue;
}

FileOutputStream fout = new FileOutputStream(path);
byte[] bytes = new byte[1024];
int c;
while((c = zip.read(bytes)) != -1){
fout.write(bytes,0, c);
}

zip.closeEntry();
fout.close();
}

}


调用(最好放到线程中):

try{
unzip(getAssets().open("data.zip"), "/mnt/sdcard");
}catch(IOException e){
e.printStackTrace();
}


ps:apk在安装的时候,无法创建自定义的文件夹,无法在应用程序中用代码控制。

apk中的资源文件并不会在安装的时候释放到某一路径中,可以通过java代码访问,但是无法获得其绝对路径,其它语言是无法直接访问的;

只能创建文件,如果连路径都没有,那是会报错的。

还有就是写文件注意加权限
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: