我有以下文件夹结构:
根文件夹 | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
我已经成功,使用以下代码获取以下 zip 文件:
result.zip--> 包含:
根文件夹 | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
我需要创建一个包含整个“RootFolder”内容的 zip 文件,而无需创建根文件夹“RootFolder”;
我的意思是我需要的结果是:
result.zip--> 包含:
| | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
public static void main(String[] args) throws Exception {
zipFolder("c:/new/RootFolder", "c:/new/result.zip");
}
static public void zipFolder(String srcFolder, String destZipFile)
throws IOException, FileNotFoundException {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile,
ZipOutputStream zip) throws IOException, FileNotFoundException {
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);
}
in.close();
}
}
static public void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws IOException, FileNotFoundException {
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);
}
}
}