我有以下文件夹结构:邮编根文件夹的内容,而不在压缩文件具有根
RootFolder | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
我已经成功了,使用下面的代码,得到以下zip文件:
结果.zip文件 - >包含:
RootFolder | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
我需要创建一个具有无需创建根文件夹“RootFolder”整个“RootFolder”内容的zip文件;
我的意思是,我需要的结果是这样的:
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);
}
}
}
我一直在努力这样做,但每次我最终都会遇到这种凌乱算法的例外。 – Echo 2013-02-25 12:21:21
@Echo,什么例外?显示你想要做的事情。 – svz 2013-02-25 12:24:07
:我试图找到最简单的解决方案:) – Echo 2013-02-25 13:05:32