Java函数:如何进行文件压缩和解压缩
发布时间:2023-11-04 17:44:32
在Java中,可以使用Java自带的zip包来进行文件压缩和解压缩操作。
文件压缩步骤如下:
1. 创建一个ZipOutputStream对象,用于将压缩文件写入输出流。
2. 使用ZipOutputStream的putNextEntry方法来创建新的压缩文件。
3. 通过创建一个FileInputStream来读取待压缩的文件,并将其写入ZipOutputStream对象。
4. 关闭ZipOutputStream对象。
文件解压缩步骤如下:
1. 创建一个ZipInputStream对象,用于读取压缩文件。
2. 使用ZipInputStream的getNextEntry方法获取压缩文件的输入流。
3. 创建一个FileOutputStream对象,用于将解压出的文件写入磁盘。
4. 使用BufferedOutputStream将ZipInputStream中的数据写入FileOutputStream。
5. 关闭ZipInputStream对象和FileOutputStream对象。
下面是一个示例代码,展示如何进行文件压缩和解压缩操作:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class FileCompression {
public static void compressFile(String sourcePath, String destinationPath) {
try {
File sourceFile = new File(sourcePath);
FileOutputStream fos = new FileOutputStream(destinationPath);
ZipOutputStream zipOut = new ZipOutputStream(fos);
FileInputStream fis = new FileInputStream(sourceFile);
ZipEntry zipEntry = new ZipEntry(sourceFile.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
zipOut.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void decompressFile(String sourcePath, String destinationPath) {
try {
FileInputStream fis = new FileInputStream(sourcePath);
ZipInputStream zipIn = new ZipInputStream(fis);
FileOutputStream fos = null;
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destinationPath + File.separator + entry.getName();
if (!entry.isDirectory()) {
fos = new FileOutputStream(filePath);
int length;
byte[] buffer = new byte[1024];
while ((length = zipIn.read(buffer)) >= 0) {
fos.write(buffer, 0, length);
}
fos.close();
} else {
File dir = new File(filePath);
dir.mkdirs();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String sourcePath = "C:\\path\\to\\file\\example.txt";
String destinationPath = "C:\\path\\to\\zipfile\\example.zip";
compressFile(sourcePath, destinationPath);
System.out.println("File compressed successfully!");
String unzipPath = "C:\\path\\to\\destination\\folder";
String zipFilePath = "C:\\path\\to\\zipfile\\example.zip";
decompressFile(zipFilePath, unzipPath);
System.out.println("File decompressed successfully!");
}
}
以上是一个简单的文件压缩和解压缩的示例代码。你可以根据自己的需求进行相应更改和优化。
