我正在使用以下Java代码,但是当它压缩文件时,它会创建一个目录并将所有内容压缩在该目录中。
例如,如果我有一个名为“Directory”的文件夹,并且想将其内容压缩到一个压缩文件中,在压缩文件中,它会创建一个名为testZip的文件夹,并在其中包含文件。
我需要所有文件都在压缩文件中,而不是在父目录中。
请帮忙解决或提供其他方法。
package folderZip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFolder {
public ZipFolder() {
}
public static void main(String[] args) throws Exception {
ZipFolder obj = new ZipFolder();
obj.zipFolder("C:\\Drive\\temp\\testZip","C:\\Drive\\temp\\FolderZiper.zip");
}
public void zipFolder(String srcFolder,
String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
private void addFileToZip(String path, String srcFile,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
private void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName,
zip);
} else {
addFileToZip(path + "/" + folder.getName(),
srcFolder + "/" + fileName, zip);
}
}
}
}
Files.walkFileTree
和FileVisitor
API遍历文件树并压缩内容。 - prasad_