问题描述
请查看以下代码。
public void startCompress(String path,String fileName,String outputLocation,int compressType,int filSize) throws Exception
{
System.out.println("Input Location: "+path);
System.out.println("Output Location: "+outputLocation);
System.out.println(compressType);
byte[] bs=new byte[filSize];
System.out.println(filSize);
FileOutputStream fos=new FileOutputStream(outputLocation+"/test.zip");
System.out.println(fos.toString());
ZipOutputStream zos=new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(fileName);
zos.putNextEntry(ze);
FileInputStream inputStream=new FileInputStream(path);
int len;
while((len=inputStream.read(bs))>0){
zos.write(bs, 0, len);
}
inputStream.close();
zos.closeEntry();
zos.close();
}
在上面的代码中,我们使用<$ c压缩文件$ c> java.util.zip 包。但我们有一个问题。也就是说,如果我们选择多个文件,则只压缩一个文件。如果我们选择一个文件夹,压缩就不起作用了。
In above code, we compress a file using java.util.zip
package. But we have an issue. That is, if we select multiple files then only one file is being compressed. If we select a folder, the compression simply won't work.
如何解决此问题以压缩文件,文件,文件夹,文件夹甚至嵌套文件夹? Java zip包支持.zip,.tar,.tarGz和tarZ。所以解决方案不应该只限于.zip扩展名。
How can I fix this to compress either a file, files, folder, folders, or even nested folders? Java zip package does support .zip, .tar, .tarGz and tarZ. So the solution should not be something which is limited to .zip extension as well.
推荐答案
不能使用java的zip库以更简单的方式压缩文件夹 - 压缩此文件夹。
The zip libraries for java cannot be used to compress folders in simpler way like - compress this folder.
如果输入是文件夹或文件,则需要自己进行测试。如果是文件 - 将其添加到zip。如果是文件夹 - 迭代文件夹并将每个文件添加到zip。对于子文件夹来说是一样的。要向Zip添加多个文件,您需要为每个文件创建ZipEntry。
You need to do the test if the input is folder or file by yourself. If it is a file - add it to the zip. If it is a folder - iterate the folder and add each file to the zip. For the subfolders to the same. To add more than one file to the Zip you need to create ZipEntry for each file.
您可以尝试这个适合我的代码:
You can try this code which works for me:
public static void zip(File directory, File zipfile) throws IOException {
URI base = directory.toURI();
Deque<File> queue = new LinkedList<File>();
queue.push(directory);
OutputStream out = new FileOutputStream(zipfile);
Closeable res = out;
try {
ZipOutputStream zout = new ZipOutputStream(out);
res = zout;
while (!queue.isEmpty()) {
directory = queue.pop();
for (File kid : directory.listFiles()) {
String name = base.relativize(kid.toURI()).getPath();
if (kid.isDirectory()) {
queue.push(kid);
name = name.endsWith("/") ? name : name + "/";
zout.putNextEntry(new ZipEntry(name));
} else {
zout.putNextEntry(new ZipEntry(name));
copy(kid, zout);
zout.closeEntry();
}
}
}
} finally {
res.close();
}
}
这篇关于如何在Java中压缩文件和文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!