我有以下文件夹结构:
根文件夹|||-->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
我需要创建一个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);
}
}
}
您需要做的是添加文件,不是从根文件夹开始,而是从其内容开始。
类似于:
filelist = getFileList(rootFolder)
foreach(File f : filelist){
addFolderToZip(f)
}
很抱歉出现伪代码,不记得原始函数名,现在无法检查它们,但它们可以很容易地在谷歌上搜索。
重点是跳过在存档中为根文件夹创建文件夹。
我已经编写了一些实用程序方法,使用NIO file API(库是开源的(将目录复制到Zip文件:
Maven:
<dependency>
<groupId>org.softsmithy.lib</groupId>
<artifactId>softsmithy-lib-core</artifactId>
<version>0.3</version>
</dependency>
教程:
http://softsmithy.sourceforge.net/lib/current/docs/tutorial/nio-file/index.html#AddZipResourceSample
API:CopyFileVisitor.copy
我试图找到解决问题的最简单方法。我决定只删除根目录名,同时使用以下方法保存在zip文件中:
String pathAfterOmittingtheRootFolder=path.replace(ROOT_FOLDER_NAME, "");
完整的方法是:
static private void addFileToZip(String path, String srcFile,
ZipOutputStream zip,String exportedRootDirectory) throws IOException, FileNotFoundException {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip,exportedRootDirectory);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
String pathAfterOmittingtheRootFolder=path.replaceFirst(exportedRootDirectory, "");
zip.putNextEntry(new ZipEntry(pathAfterOmittingtheRootFolder + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
in.close();
}
}