【发布时间】:2023-01-14 05:04:54
【问题描述】:
我想弄清楚如何将文件粘贴到 .zip 文件内的文件夹中。我使用下面的代码只是将文件添加到 zip 中,而不是其中的特定文件夹。我不允许解压缩此文件。我有一些基本的文本文件来替换 zip 中已经存在的同名文件。
如何修改此方法以选择 zip 中的特定文件夹?谢谢!
public static void addFilesToExistingZip(File zipFile, File[] files) throws IOException {
File tempFile = File.createTempFile(zipFile.getName(), null);
tempFile.delete();
zipFile.renameTo(tempFile);
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) { // Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name)); // Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
} // Close the streams
zin.close(); // Compress the files
for (int i = 0; i < files.length; i++) {
InputStream in = new FileInputStream(files[i]); // Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(files[i].getName())); // Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
} // Complete the entry
out.closeEntry();
in.close();
} // Complete the ZIP file
out.close();
tempFile.delete();
}
【问题讨论】:
-
您可以将名称设置为类似
folder\folder2\file.txt的名称,并将路径拆分为不同的段(字符串数组),这样,您就可以在使用File.isDirectory()方法检查它是否是一个目录后进入 ZipEntry。我仍然不确定这是否有效。 PS:您应该查看ZipFile课程。