阅读量:0
在Java中,可以使用java.util.zip
包中的类进行文件的压缩和解压缩。以下是一个简单的示例,演示了如何使用这些类来压缩和解压缩文件:
压缩文件
import java.io.*; import java.util.zip.*; public class ZipFileExample { public static void main(String[] args) { String inputDir = "path/to/input/directory"; String zipFilePath = "path/to/output.zip"; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) { File dir = new File(inputDir); zipDirectory(dir, zos); } catch (IOException e) { e.printStackTrace(); } } private static void zipDirectory(File dir, ZipOutputStream zos) throws IOException { if (!dir.isDirectory()) { throw new IllegalArgumentException("Input must be a directory"); } for (File file : dir.listFiles()) { if (file.isDirectory()) { zipDirectory(file, zos); } else { try (FileInputStream fis = new FileInputStream(file); ZipEntry ze = new ZipEntry(file.getName())) { zos.putNextEntry(ze); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); } } } } }
解压缩文件
import java.io.*; import java.util.zip.*; public class UnzipFileExample { public static void main(String[] args) { String zipFilePath = "path/to/input.zip"; String outputDir = "path/to/output/directory"; try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(outputDir + File.separator + fileName); if (!ze.isDirectory()) { try (FileOutputStream fos = new FileOutputStream(newFile); BufferedOutputStream bos = new BufferedOutputStream(fos)) { byte[] buffer = new byte[1024]; int length; while ((length = zis.read(buffer)) > 0) { bos.write(buffer, 0, length); } } } else { new File(outputDir + File.separator + fileName).mkdirs(); } ze = zis.getNextEntry(); } } catch (IOException e) { e.printStackTrace(); } } }
请注意,这些示例仅用于演示目的,并且假设输入和输出路径是正确的。在实际应用中,您可能需要添加额外的错误处理和验证。