/**
* 压缩文件
*
* @param zipPath 文件压缩后生成的文件路径
* @param files 需要压缩的文件
*/
public static void compressionFile(String zipPath, File[] files) throws IOException {
ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath));
for (File file : files) {
if (file.isDirectory()) {
isDirectory(zipOutputStream, file, file.getName());
} else if (file.isFile()) {
isFile(zipOutputStream, file, "");
}
}
zipOutputStream.flush();
zipOutputStream.close();
}
private static void isDirectory(ZipOutputStream zipOutputStream, File file, String pathName) throws IOException {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File file1 : files) {
if (file1.isDirectory()) {
isDirectory(zipOutputStream, file1, pathName + File.separator + file1.getName());
} else if (file1.isFile()) {
isFile(zipOutputStream, file1, pathName);
}
}
} else {
String name = pathName + "/";
ZipEntry zipEntry = new ZipEntry(name);
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.closeEntry();
}
}
private static void isFile(ZipOutputStream zipOutputStream, File file, String pathName) throws IOException {
ZipEntry zipEntry;
if (pathName == null || "".equals(pathName)) {
zipEntry = new ZipEntry(file.getName());
} else {
zipEntry = new ZipEntry(pathName + File.separator + file.getName());
}
zipOutputStream.putNextEntry(zipEntry);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] b = new byte[1024];
int l = 0;
while ((l = fileInputStream.read(b)) > 0) {
zipOutputStream.write(b, 0, l);
}
fileInputStream.close();
zipOutputStream.closeEntry();
}
/**
* 解压文件
*
* @param zipFilePath 压缩文件路径
* @param unpackPath 解压文件存放路径
*/
public static void unpackFile(String zipFilePath, String unpackPath) throws IOException {
File file = new File(zipFilePath);
ZipFile zipFile = new ZipFile(file);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String path = unpackPath + "\\" + zipEntry.getName();
new File(path).mkdirs();
if (zipEntry.isDirectory()) {
continue;
}
new File(path).delete();
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
InputStream inputStream = zipFile.getInputStream(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) > 0) {
fileOutputStream.write(bytes, 0, length);
}
inputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
zipFile.close();
zipInputStream.close();
}
Java 文件压缩与解压
最新推荐文章于 2024-04-01 11:33:49 发布