gpt4 book ai didi

java - 压缩包含子文件夹的文件夹

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:34 24 4
gpt4 key购买 nike

public static void main(String argv[]) {
try {
String date = new java.text.SimpleDateFormat("MM-dd-yyyy")
.format(new java.util.Date());
File inFolder = new File("Output/" + date + "_4D");
File outFolder = new File("Output/" + date + "_4D" + ".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();
} catch (Exception e) {
e.printStackTrace();
}
}

我正在尝试压缩一个包含子文件夹的文件夹。尝试压缩名为 10-18-2010_4D 的文件夹。上述程序以以下异常结束。请告知如何解决问题。

java.io.FileNotFoundException: Output\10-18-2010_4D\4D (Access is denied)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at ZipFile.main(ZipFile.java:17)

最佳答案

下面是创建 ZIP 存档的代码。创建的存档保留原始目录结构(如果有)。

public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception {
if (fileToZip == null || !fileToZip.exists()) {
return;
}

String zipEntryName = fileToZip.getName();
if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) {
zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
}

if (fileToZip.isDirectory()) {
System.out.println("+" + zipEntryName);
for (File file : fileToZip.listFiles()) {
addDirToZipArchive(zos, file, zipEntryName);
}
} else {
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();
}
}

不要忘记在调用此方法后关闭输出流。这是示例:

public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:\\Users\\vebrpav\\archive.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
addDirToZipArchive(zos, new File("C:\\Users\\vebrpav\\Downloads\\"), null);
zos.flush();
fos.flush();
zos.close();
fos.close();
}

关于java - 压缩包含子文件夹的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com