这是我在压缩文件夹上的代码:
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)。当Zipping Folder_1时,zip文件包含Folder_2。如何删除Folder_1.zip上的Folder_2?
这是我的观点
Main_Folder
当Zipping Folder_1包含
时我有什么方法或想法可以删除这个&#34; h&#34;在压缩文件夹中的文件夹?
答案 0 :(得分:0)
我怀疑,因为你在使用instace变量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
}
}