我有以下情况: 我可以使用以下方法压缩我的文件:
public boolean generateZip(){
byte[] application = new byte[100000];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// These are the files to include in the ZIP file
String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"};
// Create a buffer for reading the files
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(baos);
// Compress the files
for (int i=0; i<filenames.length; i++) {
byte[] filedata = VirtualFile.fromRelativePath(filenames[i]).content();
ByteArrayInputStream in = new ByteArrayInputStream(filedata);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filenames[i]));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(application)) > 0) {
out.write(application, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
System.out.println("There was an error generating ZIP.");
e.printStackTrace();
}
downloadzip(baos.toByteArray());
}
这工作得很好,我可以下载 xy.zip,其中包含以下目录和文件结构:
子目录/
----index.html
----webindex.html
我的目标是完全省略子目录,并且 zip 应该只包含这两个文件。有什么办法可以实现这一点吗? (我在 Google App Engine 上使用 Java)。
提前致谢
最佳答案
如果您确定在省略目录的情况下 filenames
数组中包含的文件是唯一的,请更改用于构造 ZipEntry
的行:
String zipEntryName = new File(filenames[i]).getName();
out.putNextEntry(new ZipEntry(zipEntryName));
关于java - 使用 util.zip 压缩文件 无目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298529/