我有以下文件夹结构:
RootFolder | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
我使用以下代码成功获取以下zip文件:
result.zip - >包含:
RootFolder | | | -->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);
}
}
}
答案 0 :(得分:1)
您需要做的是添加文件,不是以您的根文件夹开头,而是以其内容开头。
类似的东西:
filelist = getFileList(rootFolder)
foreach(File f : filelist){
addFolderToZip(f)
}
对于伪代码抱歉,不记得原来的功能名称,现在无法检查它们,但可以轻松用Google搜索。
重点是跳过在根文件夹的存档中创建文件夹。
答案 1 :(得分:1)
我已经编写了一些实用程序方法,使用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
答案 2 :(得分:0)
我试图找出解决问题的最简单方法。 我解决了这个问题,只需删除根目录名,同时使用以下命令保存在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();
}
}