如何在java中逐个压缩选定的多个文件夹
我正在尝试使用Java压缩多个文件夹。下面是我的代码如何在java中逐个压缩选定的多个文件夹,java,file,io,zip,apache-commons,Java,File,Io,Zip,Apache Commons,我正在尝试使用Java压缩多个文件夹。下面是我的代码 if (CompressType.ZIP == zip){ File f = null; for (File serlectFile : serlectFiles){ f = new File(serlectFile.getAbsolutePath()); filePath = f; System.out.println("NIO Folders 1122 : " + fi
if (CompressType.ZIP == zip){
File f = null;
for (File serlectFile : serlectFiles){
f = new File(serlectFile.getAbsolutePath());
filePath = f;
System.out.println("NIO Folders 1122 : " + filePath);
new Thread(new Runnable(){
public void run(){
try{
compressFolder.createZip(filePath.getPath(), destination.getPath());
JOptionPane.showMessageDialog(null, " Backup Created .....", "Alert", 1);
dispose();
} catch (IOException ex){
JOptionPane.showMessageDialog(null, "Error ! ");
ex.printStackTrace();
}
}
}).start();
}
}
这是我尝试执行上述任务的代码。但不幸的是我没能完成。因为当我将“filepath.getPath()”发送到“createZip()”方法时,它一次只得到一个目录。但是当我在调用它的方法之前打印filepath时,它给了我以下信息NIO文件夹1122:C:\Users\user\Desktop\backup“”-
“”NIO文件夹1122:C:\Users\user\Desktop\contact“”
我能想到的原因是,应用程序正在运行,而不需要等待一个线程完成。因此,所有线程都在循环中运行。下面是我的压缩代码,它在上述线程中运行
public void createZip(String directoryPath, String zipPath) throws IOException{
value = countFilesInDirectory(new File(directoryPath));
ExpressWizard.backupProgressBar.setMaximum(value);
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
ZipArchiveOutputStream tOut = null;
try{
fOut = new FileOutputStream(new File(zipPath));
bOut = new BufferedOutputStream(fOut);
tOut = new ZipArchiveOutputStream(bOut);
addFileToZip(tOut, directoryPath, "");
} finally {
tOut.finish();
tOut.close();
bOut.close();
fOut.close();
}
}
@SuppressWarnings("empty-statement")
private void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException{
File f = new File(path);
String entryName = base + f.getName();
ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);
zOut.putArchiveEntry(zipEntry);
if (f.isFile()) {
FileInputStream fInputStream = null;
try{
fInputStream = new FileInputStream(f);
IOUtils.copy(fInputStream, zOut);
zOut.closeArchiveEntry();
} finally {
IOUtils.closeQuietly(fInputStream);
}
System.out.println(f.getAbsolutePath());
counter++;
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
ExpressWizard.backupProgressBar.setValue(counter);
ExpressWizard.filesTextArea.append(f.getAbsolutePath() + "\n");
}
});
if (ExpressWizard.backupProgressBar.getValue() == counter){
ExpressWizard.backUpButton.setEnabled(false);
}
} else{
zOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null){
for (File child : children){
addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
System.out.println("File: " + child.getAbsolutePath());
}
}
}
}
如何一个接一个地执行此代码?换句话说,zip文件线程应该为一个文件夹运行;循环应该等待;压缩完成后,第二个文件夹开始压缩;循环等待线程结束;然后是第三个文件夹,依此类推
有什么想法吗