Здесь мой код на Zipping Folder:
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();
}
}
Моя проблема: у меня есть 2 папки (Folder_1 и Folder_2) в одном каталоге (Main_Folder). Когда Zipping Folder_1, zip файл включает Folder_2. Как удалить Folder_2 на моем Folder_1.zip?
Здесь мой пункт
Main_Folder
Когда Zipping Folder_1 состоит из
Есть ли какой-нибудь метод или идеи для удаления этой "h" папки в папку с zipping?
Я подозреваю, что с тех пор, как вы используете файлы переменной filesListInDir
для хранения файлов перед тем, как 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
}
}