我們在日常生活中會用到解壓縮,這個是非常重要的,那么我們在android系統中有沒有解壓縮那。如果有的話,那我們如何實現Zip文件的解壓縮功能呢? 那么我們就看看下面的解析吧,因為Android內部已經集成了zlib庫,對於英文和非密碼的Zip文件解壓縮還是比較簡單的,下面給大家一個解壓縮zip的java代碼,可以在Android上任何版本中使用,Unzip這個靜態方法比較簡單,參數一為源zip文件的完整路徑,參數二為解壓縮后存放的文件夾。希望這段代碼能教會大家解壓縮。
private static void Unzip(String zipFile, String targetDir) {
int BUFFER = 4096; //這里緩沖區我們使用4KB,
String strEntry; //保存每個zip的條目名稱
try {
BufferedOutputStream dest = null; //緩沖輸出流
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; //每個zip條目的實例
while ((entry = zis.getNextEntry()) != null) {
try {
Log.i("Unzip: ","="+ entry);
int count;
byte data[] = new byte[BUFFER];
strEntry = entry.getName();
File entryFile = new File(targetDir + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists()) {
entryDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
zis.close();
} catch (Exception cwj) {
cwj.printStackTrace();
}
}
上面是Android開發網總結的zip文件解壓縮代碼,希望你大家有用,需要注意的是參數均填寫完整的路徑,比如/mnt/sdcard/xxx.zip這樣的類型。
下面的方法是,解壓只有一個文件組成的zip到當前目錄,並且給解壓出的文件重命名:
public static void unzipSingleFileHereWithFileName(String zipPath, String name) throws IOException{
File zipFile = new File(zipPath);
File unzipFile = new File(zipFile.getParent() + "/" + name);
ZipInputStream zipInStream = null;
FileOutputStream unzipOutStream = null;
try {
zipInStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInStream.getNextEntry();
if (!zipEntry.isDirectory()) {
unzipOutStream = new FileOutputStream(unzipFile);
byte[] buf = new byte[4096];
int len = -1;
while((len = zipInStream.read(buf)) != -1){
unzipOutStream.write(buf, 0, len);
}
}
} finally {
if(unzipOutStream != null){
unzipOutStream.close();
}
if (zipInStream != null) {
zipInStream.close();
}
}
}