android 代码解压,Android开发之旅-解压压缩zip文件(带子目录和中文路径)
今天弄了一下午解壓的問題,需求嘛,把自己踩過的坑記錄下來,也為了跟我一樣的新人少坑的路。
怎么那么多的屁話,上代碼啊!
上解壓的代碼:
//第一個參數就是需要解壓的文件,第二個就是解壓的目錄
public static boolean upZipFileDir(File zipFile, String folderPath) {
ZipFile zfile= null;
try {
//轉碼為GBK格式,支持中文
zfile = new ZipFile(zipFile,"GBK");
} catch (IOException e) {
e.printStackTrace();
return false;
}
Enumeration zList=zfile.getEntries();
ZipEntry ze=null;
byte[] buf=new byte[1024];
while(zList.hasMoreElements()){
ze=(ZipEntry)zList.nextElement();
//列舉的壓縮文件里面的各個文件,判斷是否為目錄
if(ze.isDirectory()){
String dirstr = folderPath + ze.getName();
dirstr.trim();
File f=new File(dirstr);
f.mkdir();
continue;
}
OutputStream os= null;
FileOutputStream fos = null;
// ze.getName()會返回 script/start.script這樣的,是為了返回實體的File
File realFile = getRealFileName(folderPath, ze.getName());
try {
fos = new FileOutputStream(realFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
os = new BufferedOutputStream(fos);
InputStream is= null;
try {
is = new BufferedInputStream(zfile.getInputStream(ze));
} catch (IOException e) {
e.printStackTrace();
return false;
}
int readLen=0;
//進行一些內容復制操作
try {
while ((readLen=is.read(buf, 0, 1024))!=-1) {
os.write(buf, 0, readLen);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
try {
zfile.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 給定根目錄,返回一個相對路徑所對應的實際文件名.
* @param baseDir 指定根目錄
* @param absFileName 相對路徑名,來自于ZipEntry中的name
* @return java.io.File 實際的文件
*/
public static File getRealFileName(String baseDir, String absFileName){
String[] dirs=absFileName.split("/");
File ret = new File(baseDir);
String substr = null;
if(dirs.length>1){
for (int i = 0; i < dirs.length-1;i++) {
substr = dirs[i];
ret=new File(ret, substr);
}
if(!ret.exists())
ret.mkdirs();
substr = dirs[dirs.length-1];
ret=new File(ret, substr);
return ret;
}else{
ret = new File(ret,absFileName);
}
return ret;
}
記得別用系統提供的java.util.zip.ZipFile這個類,沒辦法支持中文的。
去下載 ZipEntry.jar引用到項目中即可。
總結
以上是生活随笔為你收集整理的android 代码解压,Android开发之旅-解压压缩zip文件(带子目录和中文路径)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle mysql安装步骤_Ora
- 下一篇: java通讯录带报告