我有以下文件夹结构:
RootFolder | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
I have succeed,using the following code,to get the following zip file:
result.zip--> that contains:
RootFolder | | | -->F1-->F1.1-->t1.txt,t2.txt -->F2-->F2.2-->t3.txt
I need to create a zip file that has the whole "RootFolder" content without creating a root folder"RootFolder";
I mean I need the result to be like:
result.zip--> that contains:
| | | -->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)
}
抱歉,伪代码,不记得原始函数名称,现在无法检查它们,但可以轻松通过谷歌搜索它们。
重点是跳过在根文件夹的存档中创建文件夹的步骤。
关于java - 压缩根文件夹内容,但 zip 文件没有根目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15066445/