java分卷压缩代码实现可以运行出结果
时间: 2023-03-02 17:34:26 浏览: 73
以下是Java中使用分卷压缩的代码实现:
```java
import java.io.*;
import java.util.zip.*;
public class ZipUtils {
private static final int BUFFER_SIZE = 4096;
/**
* 将指定文件或文件夹压缩成zip文件
* @param sourcePath 源文件或文件夹路径
* @param zipPath 压缩后的zip文件路径
* @throws IOException
*/
public static void zip(String sourcePath, String zipPath) throws IOException {
FileOutputStream fos = new FileOutputStream(zipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File sourceFile = new File(sourcePath);
if (sourceFile.isDirectory()) {
// 如果是文件夹,则递归压缩其所有子文件和子文件夹
zipFolder(sourceFile, zos, "");
} else {
// 如果是文件,则直接压缩
zipFile(sourceFile, zos, "");
}
zos.close();
fos.close();
}
private static void zipFolder(File folder, ZipOutputStream zos, String parentPath) throws IOException {
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
// 如果是子文件夹,则递归调用zipFolder方法
zipFolder(file, zos, parentPath + folder.getName() + "/");
} else {
// 如果是文件,则调用zipFile方法
zipFile(file, zos, parentPath + folder.getName() + "/");
}
}
}
private static void zipFile(File file, ZipOutputStream zos, String parentPath) throws IOException {
FileInputStream fis = new FileInputStream(file);
// 添加ZipEntry
zos.putNextEntry(new ZipEntry(parentPath + file.getName()));
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
/**
* 将指定zip文件解压到指定目录下
* @param zipPath zip文件路径
* @param destPath 目标目录路径
* @throws IOException
*/
public static void unzip(String zipPath, String destPath) throws IOException {
File destFile = new File(destPath);
if (!destFile.exists()) {
destFile.mkdirs();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipPath));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String entryPath = destPath + File.separator + entry.getName();
if (entry.isDirectory()) {
File entryFile = new File(entryPath);
entryFile.mkdirs();
} else {
// 如果是文件,则写入到磁盘
FileOutputStream fos = new FileOutputStream(entryPath);
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = zis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
zis.closeEntry();
}
zis.close();
}
}
```
使用时,可以在main函数中调用ZipUtils的zip方法压缩文件,或调用unzip方法解压缩文件。例如:
```java
public static void main(String[] args) {
String sourcePath = "C:/