使用java在一个输出中压缩多个文件夹和文件



所以我在一个项目中工作,当我需要压缩多个文件夹(具体为4个文件夹)和一个文件在一个output.zip文件使用java我可以这么做吗顺便说一下,把所有文件夹和文件放在一个目录下然后压缩不会得到相同的结果换句话说,文件夹必须在zip文件的根目录下

有几种解决方案。例如:


public static void zipDirectory(ZipOutputStream zos, File fileToZip, String parentDirectoryName) throws Exception
{
if (fileToZip == null || !fileToZip.exists())
{
return;
}
String zipEntryName = fileToZip.getName();
if (parentDirectoryName!=null && !parentDirectoryName.isEmpty())
{
zipEntryName = parentDirectoryName + "/" + fileToZip.getName();
}
// If we are dealing with a directory:
if (fileToZip.isDirectory())
{
System.out.println("+" + zipEntryName);
if(parentDirectoryName == null) // if parentDirectory is null, that means it's the first iteration of the recursion, so we do not include the first container folder
{
zipEntryName = "";
}
for (File file : fileToZip.listFiles()) // we iterate over all the folders/files and archive them by keeping the structure too.
{
zipDirectory(zos, file, zipEntryName);
}
} else // If we are dealing with a file, then we zip it directly
{
System.out.println("   " + zipEntryName);
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(fileToZip);
zos.putNextEntry(new ZipEntry(zipEntryName));
int length;
while ((length = fis.read(buffer)) > 0)
{
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}

那么你可以像这样使用这个函数:

try
{
File directoryToBeZipped = new File("C:\New\test");
FileOutputStream fos = new FileOutputStream("C:\New\test\archive.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zipDirectory(zos, directoryToBeZipped, null);
zos.flush();
fos.flush();
zos.close();
fos.close();

} catch (Exception e) 
{
e.printStackTrace();
}

或者您可以使用ZeroTurnAround ZIP库。在一行中完成:

ZipUtil.pack(new File("D:\sourceFolder\"), new File("D:\generatedZipFile.zip"));

非常简单的方法(尽管你会得到关于专有类的警告)

final String[] ARGS = { "-cfM", "x.zip", "folder1", "folder2", "folder3", "folder4", "file.txt" };
sun.tools.jar.Main.main(ARGS);

可能值得得到一个类似的东西,不会给你警告

最新更新