在Java中,可以使用第三方庫Apache Commons Compress來實現(xiàn)文件的壓縮和解壓。以下是一個簡單的示例,演示了如何使用Apache Commons Compress進行文件的壓縮和解壓。
<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();
}
}
}
這樣就可以實現(xiàn)文件的壓縮和解壓了。注意,這里的示例是針對ZIP格式的壓縮文件,如果需要處理其他格式的壓縮文件,可以參考Apache Commons Compress的文檔進行相應(yīng)的修改。