阅读量:0
在Java中,可以使用第三方库Apache Commons Compress来实现文件的压缩和解压。以下是一个简单的示例,演示了如何使用Apache Commons Compress进行文件的压缩和解压。
- 首先,需要将Apache Commons Compress库添加到项目中。如果你使用Maven,可以在pom.xml文件中添加以下依赖:
<groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.21</version> </dependency>
- 接下来,编写一个方法来压缩文件:
import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.*; public class FileCompressor { public static void compressFile(File inputFile, File outputFile) throws IOException { try (OutputStream fileOutputStream = new FileOutputStream(outputFile); ArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(fileOutputStream)) { ZipArchiveEntry entry = new ZipArchiveEntry(inputFile.getName()); archiveOutputStream.putArchiveEntry(entry); try (InputStream inputStream = new FileInputStream(inputFile)) { IOUtils.copy(inputStream, archiveOutputStream); } archiveOutputStream.closeArchiveEntry(); } } }
- 编写一个方法来解压文件:
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.utils.IOUtils; import java.io.*; public class FileDecompressor { public static void decompressFile(File inputFile, File outputDirectory) throws IOException { try (InputStream fileInputStream = new FileInputStream(inputFile); ArchiveInputStream archiveInputStream = new ZipArchiveInputStream(fileInputStream)) { ArchiveEntry entry; while ((entry = archiveInputStream.getNextEntry()) != null) { File outputFile = new File(outputDirectory, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { outputFile.mkdirs(); } } else { try (OutputStream outputStream = new FileOutputStream(outputFile)) { IOUtils.copy(archiveInputStream, outputStream); } } } } } }
- 最后,在主程序中调用这两个方法来压缩和解压文件:
public class Main { public static void main(String[] args) { File inputFile = new File("path/to/your/input/file"); File compressedFile = new File("path/to/your/compressed/file.zip"); File outputDirectory = new File("path/to/your/output/directory"); try { // 压缩文件 FileCompressor.compressFile(inputFile, compressedFile); // 解压文件 FileDecompressor.decompressFile(compressedFile, outputDirectory); } catch (IOException e) { e.printStackTrace(); } } }
这样就可以实现文件的压缩和解压了。注意,这里的示例是针对ZIP格式的压缩文件,如果需要处理其他格式的压缩文件,可以参考Apache Commons Compress的文档进行相应的修改。