一、解压zip文件:
/**
* 解压缩文件(压缩文件中可含子目录)
* @param zipFilePath 压缩文件完整路径
* @param targetDir 要解压到的地方的完整路径
* @throws IOException
*/
public static void unZip(String zipFilePath, String targetDir) throws IOException
{
long startTime = 0, endTime;
int BUFFER = 4096; // 每次读取的缓冲区设为4KB
String strEntry; // zip中文件名称
ZipEntry entry;
ZipFile zipFile = new ZipFile(zipFilePath, "GBK"); // 如果压缩包中有中文命名的文件,加上“GBK”可避免解压缩后出现乱码的情况
Enumeration<?> enu = zipFile.getEntries();
startTime = System.currentTimeMillis();
System.out.println("开始时间: " + startTime);
while (enu.hasMoreElements())
{
entry = (ZipEntry) enu.nextElement();
int count;
byte[] data = new byte[BUFFER];
strEntry = entry.getName();
if (entry.isDirectory())
{ // 如果是子文件夹/目录,则在目标路径新建子文件夹/目录
File file = new File(targetDir + File.separator + strEntry);
if (!file.exists()) {
file.mkdirs();
}
}
else
{ // 如果是文件,则直接解压到目标路径
File entryFile = new File(targetDir + "/" + strEntry);
File entryDir = new File(entryFile.getParent());
if (!entryDir.exists())
{
entryDir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
OutputStream bufout = new BufferedOutputStream(fos, BUFFER);
InputStream bufis = new BufferedInputStream(zipFile.getInputStream(entry));
while ((count = bufis.read(data, 0, BUFFER)) != -1) {
bufout.write(data, 0, count);
}
bufout.flush();
bufis.close();
bufout.close();
}
}
endTime = System.currentTimeMillis();
System.out.println("结束时间: " + endTime);
System.out.println("用时 :" + (endTime - startTime) + "ms");
zipFile.close();
}
因为java的api在解压zip包中有中文命名的文件时会出现乱码。所以要用到第三方jar包——ant.jar:
二、压缩文件成.zip:
File zipFile = new File(Environment.getExternalStorageDirectory().toString() + "/target.zip");
File targetDir = new File(Environment.getExternalStorageDirectory().toString() + "/xxx");
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(new FileOutputStream(zipFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
File[] entries = targetDir.listFiles();
for (int i = 0; i < entries.length; i++) {
try {
zipFile(zos, entries[i], "");
} catch (IOException e) {
e.printStackTrace();
}
}
以下是压缩文件的核心代码:
private void zipFile(ZipOutputStream zos, File fileOrDirectory, String curPath) throws IOException {
FileInputStream fin = null;
try {
if (fileOrDirectory.isFile())
{ // 压缩文件
byte[] buffer = new byte[4096];
int bytes_read;
fin = new FileInputStream(fileOrDirectory);
ZipEntry entry = new ZipEntry(curPath + fileOrDirectory.getName());
zos.putNextEntry(entry);
while ((bytes_read = fin.read(buffer)) != -1) {
zos.write(buffer, 0, bytes_read);
}
zos.closeEntry();
}
else if (fileOrDirectory.isDirectory())
{ // 压缩文件夹
File[] entries = fileOrDirectory.listFiles();
for (File file : entries) {
// 递归压缩,更新curPath
zipFile(zos, file, curPath + fileOrDirectory.getName() + "/");
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null) {
fin.close();
}
}
}
同样需要引入Apache 的ant.jar包