本教程介绍如何利用Java中的org.apache.tools.zip库有效处理文件解压缩过程中遇到的编码问题,确保文件内容正确显示。
```java
package com.cliff.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
/**
* 类名: ZipUtil.java
* 描述:压缩/解压缩zip包处理类
* 创建者:XXX
* 创建日期:2015年5月7日 - 下午1:35:02
* 版本: V0.1
*/
public class ZipUtil {
/**
* 功能描述:压缩文件
* 创建者:XXX
* 创建日期: 2015年5月7日 - 下午1:35:18
* 版本: V0.1
*/
public static void zip(String directory) throws FileNotFoundException, IOException {
zip(, null, directory);
}
/**
* 功能描述:压缩文件
* 创建者:XXX
* 创建日期: 2015年5月7日 - 下午1:36:03
* 版本: V0.1
*/
public static void zip(String zipFileName, String relativePath, String directory) throws FileNotFoundException, IOException {
String fileName = zipFileName;
if (fileName == null || fileName.trim().equals()) {
File temp = new File(directory);
if (temp.isDirectory()) {
fileName = directory + .zip;
} else {
if (directory.indexOf(.) > 0) {
fileName = directory.substring(0, directory.lastIndexOf(.))+ zip;
} else {
fileName = directory + .zip;
}
}
}
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName));
try {
zip(zos, relativePath, directory);
} catch (IOException ex) {
throw ex;
} finally {
if (null != zos) {
zos.close();
}
}
}
/**
* 功能描述:压缩文件
* 创建者:XXX
* 创建日期: 2015年5月7日 - 下午1:37:55
* 版本: V0.1
*/
private static void zip(ZipOutputStream zos, String relativePath, String absolutPath) throws IOException {
File file = new File(absolutPath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File tempFile = files[i];
if (tempFile.isDirectory()) {
String newRelativePath = relativePath + tempFile.getName() + File.separator;
createZipNode(zos, newRelativePath);
zip(zos, newRelativePath, tempFile.getPath());
} else {
zipFile(zos, tempFile, relativePath);
}
}
} else {
zipFile(zos, file, relativePath);
}
}
/**
* 功能描述:压缩文件
* 创建者:XXX
* 创建日期: 2015年5月7日 - 下午1:38:46
* 版本: V0.1
*/
private static void zipFile(ZipOutputStream zos, File file, String relativePath) throws IOException {
ZipEntry entry = new ZipEntry(relativePath + file.getName());
zos.putNextEntry(entry);
InputStream is = null;
try {
is = new FileInputStream(file);
int BUFFERSIZE = 2 << 10;
int length = 0; byte[] buffer = new byte[BUFFERSIZE];
while ((length = is.read(buffer, 0, BUFFERSIZE)) >= 0) {
zos.write(buffer, 0, length);
}
zos.flush();
zos.closeEntry();
} catch (IOException ex) { throw ex; } finally {
if (null != is) {
is.close();
}
}
}
/**
* 功能描述:创建目录
* 创建者:XXX
* 创建日期: 2015年5月7日 - 下午1:39:12
* 版本: V0.1
*/
private static void createZipNode(ZipOutputStream zos, String relativePath) throws IOException {
ZipEntry zipEntry = new ZipEntry(relativePath);
zos.putNextEntry(zipEntry);
zos.closeEntry();
}
/**
* 功能描述:解压缩文件
* 创建者:XXX
* 创建日期: 201