如何编写Java函数实现文件压缩和解压缩操作?
发布时间:2023-11-09 13:00:27
在Java中实现文件压缩和解压缩操作可以使用Java的压缩和解压缩类库。Java提供了java.util.zip包来处理压缩和解压缩操作。下面详细介绍如何编写Java函数实现文件压缩和解压缩操作。
一、文件压缩操作:
步骤1:导入java.util.zip和java.io包
import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;
步骤2:创建一个函数来实现文件压缩操作,函数参数为要压缩的文件路径和压缩后的文件名。
public static void compress(String srcFilePath, String destFileName) throws IOException {
FileOutputStream fos = new FileOutputStream(destFileName); // 创建压缩包文件输出流
ZipOutputStream zos = new ZipOutputStream(fos); // 创建压缩输出流
File file = new File(srcFilePath); // 要压缩的文件
String basePath = ""; // 压缩的根目录
compress(file, basePath, zos); // 调用压缩文件的函数
zos.close(); // 关闭压缩输出流
fos.close(); // 关闭文件输出流
}
步骤3:创建递归函数来压缩文件夹及其子文件和子文件夹。
public static void compress(File file, String basePath, ZipOutputStream zos) throws IOException {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
compress(f, basePath + file.getName() + File.separator, zos);
}
} else {
String filePath = file.getPath();
String entryPath = basePath + file.getName();
FileInputStream fis = new FileInputStream(filePath);
ZipEntry entry = new ZipEntry(entryPath);
zos.putNextEntry(entry);
int len;
byte[] buf = new byte[1024];
while ((len = fis.read(buf)) != -1) {
zos.write(buf, 0, len);
}
fis.close();
}
}
二、文件解压缩操作:
步骤1:导入java.util.zip和java.io包。
import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException;
步骤2:创建一个函数来实现文件解压缩操作,函数参数为要解压的文件路径和解压后的文件夹路径。
public static void decompress(String srcFilePath, String destDirPath) throws IOException {
FileInputStream fis = new FileInputStream(srcFilePath); // 创建压缩文件输入流
ZipInputStream zis = new ZipInputStream(fis); // 创建解压输入流
File destDir = new File(destDirPath);
if (!destDir.exists()) { // 判断目标文件夹是否存在,不存在则创建
destDir.mkdirs();
}
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String entryName = entry.getName();
String filePath = destDirPath + File.separator + entryName;
if (entry.isDirectory()) { // 如果是文件夹则创建
File dir = new File(filePath);
dir.mkdir();
} else {
FileOutputStream fos = new FileOutputStream(filePath);
int len;
byte[] buf = new byte[1024];
while ((len = zis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.close();
}
}
zis.close(); // 关闭解压输入流
fis.close(); // 关闭文件输入流
}
三、调用函数进行压缩和解压缩操作:
public static void main(String[] args) {
String srcFilePath = "C:/path/to/source/file"; // 要压缩或解压的文件路径
String destFilePath = "C:/path/to/destination/file"; // 压缩或解压后的文件路径
try {
// 压缩文件
compress(srcFilePath, destFilePath);
// 解压缩文件
decompress(srcFilePath, destFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
以上就是Java实现文件压缩和解压缩的基本步骤和代码示例。通过使用Java提供的压缩和解压缩类库,可以方便地实现文件的压缩和解压缩操作。
