import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class DeleteFileFromZip {
public static void main(String[] args) {
String zipFilePath = "path/to/your/archive.zip";
String fileToDelete = "file-to-delete.txt";
String tempFilePath = "path/to/temporary/temp.zip";
try {
File originalFile = new File(zipFilePath);
File tempFile = new File(tempFilePath);
try (FileInputStream fileInputStream = new FileInputStream(originalFile);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
String entryName = entry.getName();
// Skip the file you want to delete
if (entryName.equals(fileToDelete)) {
continue;
}
// Copy the non-deleted file to the temporary ZIP file
zipOutputStream.putNextEntry(new ZipEntry(entryName));
byte[] buffer = new byte[1024];
int length;
while ((length = zipInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
}
}
// Replace the original ZIP file with the temporary file
originalFile.delete();
tempFile.renameTo(originalFile);
System.out.println("File '" + fileToDelete + "' has been deleted from the ZIP archive.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
删除zip压缩包里面的文件
最新推荐文章于 2024-07-10 21:37:49 发布