我正在尝试在我的机器上压缩以下文件结构,
parent/
parent/test1
parent/test1/image1.jpeg
parent/test2
这里的问题是我无法使用 java 压缩上述文件结构。我有谷歌并找到以下代码示例,但它仅将文件压缩到给定文件夹中。
File inFolder=new File("out");
File outFolder=new File("Out.zip");
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(new FileOutputStream(outFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inFolder.list();
for (int i=0; i<files.length; i++)
{
in = new BufferedInputStream(new FileInputStream
(inFolder.getPath() + "/" + files[i]), 1000);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while((count = in.read(data,0,1000)) != -1)
{
out.write(data, 0, count);
}
out.closeEntry();
}
out.flush();
out.close();
在上面的代码中,out 是一个文件夹,我们需要有一些文件。如果文件夹不能为空,它会抛出异常 java.util.zip.ZipException 或不能包含任何子文件夹,甚至其中的文件(例如:out \newfolder\image.jpeg) 如果是这样,它会抛出 java.io.FileNotFoundException: out\newfolder (访问被拒绝)。
在我的情况下,我通过查询数据库来构建上述文件结构,有时可以拥有沿文件夹结构的空文件夹。
有人可以告诉我一个解决方案吗?
谢谢你。