要實現批量解壓文件,可以使用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對象并輸出解壓成功的消息。