我有以下情况: 我可以使用以下方法压缩文件:
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)。
提前致谢
答案 0 :(得分:3)
如果您确定filenames
数组中包含的文件在您遗漏目录时是唯一的,请更改构建ZipEntry
的行:
String zipEntryName = new File(filenames[i]).getName();
out.putNextEntry(new ZipEntry(zipEntryName));
答案 1 :(得分:1)
您可以使用Apache Commons io列出所有文件,然后将其读取为InputStream
替换
下面的行String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"}
以下
Collection<File> files = FileUtils.listFiles(new File("/subdirectory"), new String[]{"html"}, true);
for (File file : files)
{
FileInputStream fileStream = new FileInputStream(file);
byte[] filedata = IOUtils.toByteArray(fileStream);
//From here you can proceed with your zipping.
}
如果您有问题,请告诉我。
答案 2 :(得分:0)
您可以在isDirectory()
VirtualFile
方法