要实现批量解压文件,可以使用Java中的ZipFile和ZipEntry类来实现。以下是一个简单的示例代码,用于批量解压文件:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class UnzipFiles { public static void main(String[] args) { String zipFilePath = "path/to/zip/file.zip"; String outputFolder = "path/to/output/folder"; try { ZipFile zipFile = new ZipFile(zipFilePath); Enumeration extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(outputFolder, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { InputStream entryInputStream = zipFile.getInputStream(entry); FileOutputStream entryOutputStream = new FileOutputStream(entryDestination); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = entryInputStream.read(buffer)) != -1) { entryOutputStream.write(buffer, 0, bytesRead); } entryInputStream.close(); entryOutputStream.close(); } } zipFile.close(); System.out.println("Files unzipped successfully."); } catch (IOException e) { System.err.println("Error unzipping files: " + e.getMessage()); } } }
在这个示例代码中,首先指定要解压的ZIP文件路径和输出文件夹路径。然后使用ZipFile类打开ZIP文件,并获取所有文件条目。遍历每个文件条目,如果是目录则创建目录,如果是文件则将文件内容读取并写入到输出文件。最后关闭ZipFile对象并输出解压成功的消息。