2013-02-21 87 views
0

我想壓縮文件夾的內容。這意味着當我解壓縮zip我不想得到文件夾,但文件夾的內容。內容是各種文件和子文件夾文件夾Java的Zip內容

問題:但是,當我這樣做時,創建的壓縮文件不顯示我的文件,它只顯示文件夾。當我使用不同的解壓縮工具時,我可以看到文件在那裏。感覺就像應用了某種安全設置,或者它們被隱藏起來。我需要能夠看到文件,因爲它導致我的其他程序出現問題。

結構應該像這樣

  • 拉鍊
    • my.html
    • my.css
    • otherfolder

不喜歡這個

  • 拉鍊
    • MyFolder文件
      • my.html
      • my.css
      • otherfolder

這裏是我使用

代碼
//create flat zip 
    FileOutputStream fileWriter = new FileOutputStream(myfolder +".zip"); 
    ZipOutputStream zip = new ZipOutputStream(fileWriter); 
    File folder = new File(myfolder); 
    for (String fileName: folder.list()) { 
     FileUtil.addFileToZip("", myfolder + "/" + fileName, zip); 
    } 
    zip.flush(); 
    zip.close(); 
//end create zip 

下面是代碼在我FileUtil

public static void addFileToZip(String path, String srcFile,ZipOutputStream zip) throws IOException { 
     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); 
      } 
      zip.closeEntry(); 
      zip.flush(); 
      in.close(); 
      //zip.close(); 
     } 
    } 

    public static void addFolderToZip(String path, String srcFolder, ZipOutputStream zip) throws IOException { 
     File folder = new File(srcFolder); 
     //System.out.println("Source folder is "+srcFolder+" into file "+folder); 
     for (String fileName: folder.list()) { 
      if (path.equals("")) { 
      addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip); 
      } 
      else { 
      //System.out.println("zipping "+path + "/" + folder.getName()+" and file "+srcFolder + "/" + fileName); 
      addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip); 
      } 
     } 
     } 

感謝您提前任何幫助,我覺得這就是我可能會在這裏失去了次要的東西。

回答

3

addFileToZip方法,你有

zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); 

你會得到一個"/"附有folder.getName()path是空白。這可能是你的問題?

嘗試

if (path.equals("")) { 
    zip.putNextEntry(new ZipEntry(folder.getName())); 
} 
else { 
    zip.putNextEntry(new ZipEntry(path + "/" + folder.getName())); 
}