gpt4 book ai didi

JAVA:压缩文件夹的问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:50 26 4
gpt4 key购买 nike

这是我在压缩文件夹上的代码:

List<String> filesListInDir = new ArrayList<String>();
public void populateFilesList(File dir) throws IOException {
File[] files = dir.listFiles();
for(File file : files){
if(file.isFile()) filesListInDir.add(file.getAbsolutePath());
else populateFilesList(file);
}
}
public void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String filePath : filesListInDir){
System.out.println("Zipping "+filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

我的问题是我在一个目录(Main_Folder)中有2个文件夹(Folder_1和Folder_2)。压缩Folder_1时,zip文件包含Folder_2。如何删除Folder_1.zip 中的Folder_2?

这是我的观点

  • Main_Folder

    • 文件夹_1
      • asd.sql
      • asd2.sql
      • asd3.sql
    • Folder_2
      • asd.jar

压缩Folder_1时,它包含以下内容

  • Folder_1.zip
    • h//该文件夹包含Folder_2 上的文件。所以我需要删除这个文件夹
    • asd.sql
    • asd2.sql
    • asd3.sql

我有什么方法或想法可以删除压缩文件夹中的这个“h”文件夹吗?

最佳答案

我怀疑,因为您在压缩之前使用实例变量filesListInDir来存储文件您之前已经在其中加载了文件,最好清除 zipDirectory 末尾的文件,并且我假设您没有在多线程环境中使用它,因为它会因为状态变量而发挥奇怪的作用.

public void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String filePath : filesListInDir){
System.out.println("Zipping "+filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
filesListInDir.clear(); // Clear the files
}
}

关于JAVA:压缩文件夹的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27617651/

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