2015-10-18 75 views
0

我在創建zip文件時出現問題,該文件包含項目結構之外的文件(例如:C:/ folder/subfolder)。什麼情況是,zip文件將包含在整個文件夾結構中的文件都放在 這裏是代碼:Java創建zip文件與整個文件夾結構的內容

public static void main(String[] args) { 
     try { 
      FileOutputStream fos = new FileOutputStream("f:/arhiva.zip"); 
      ZipOutputStream zos = new ZipOutputStream(fos); 

      String file1Name = "c:/zer/HOTTT.pdf"; 
      String file2Name = "c:/zer/fisx.docx"; 
      String file3Name = "c:/zer/fisx.xlsx"; 

      addToZipFile(file1Name, zos); 
      addToZipFile(file2Name, zos); 
      addToZipFile(file3Name, zos); 

      zos.close(); 
      fos.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 


    public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException { 

      System.out.println("Writing '" + fileName + "' to zip file"); 

      File file = new File(fileName); 
      FileInputStream fis = new FileInputStream(file); 
      ZipEntry zipEntry = new ZipEntry(fileName); 
      zos.putNextEntry(zipEntry); 

      byte[] bytes = new byte[1024]; 
      int length; 
      while ((length = fis.read(bytes)) >= 0) { 
       zos.write(bytes, 0, length); 
      } 

      zos.closeEntry(); 
      fis.close(); 
     } 

請幫幫我!

回答

0

我已經解決了這個問題。看來使用Path可以解決問題。

public static void main(String[] args) { 
     try { 
      FileOutputStream fos = new FileOutputStream("f:/arhivaB.zip"); 
      ZipOutputStream zos = new ZipOutputStream(fos); 

      Path calea = Paths.get("c:\\bin\\HOTTT.pdf"); 
      File fisa = calea.toFile(); 
      Path caleb = Paths.get("c:\\bin\\fisx.docx"); 
      File fisb = caleb.toFile(); 
      Path calec = Paths.get("c:\\bin\\fisx.xlsx"); 
      File fisc = calec.toFile(); 


      addToZipFile(fisa, zos); 
      addToZipFile(fisb, zos); 
      addToZipFile(fisc, zos); 
//   addToZipFile(file1Name, zos); 
//   addToZipFile(file2Name, zos); 
//   addToZipFile(file3Name, zos); 

      zos.close(); 
      fos.close(); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void addToZipFile(/*String fileName*/ File fisa, ZipOutputStream zos) throws FileNotFoundException, IOException { 

//  System.out.println("Writing '" + fileName + "' to zip file"); 

//  File file = new File(fileName); 
     FileInputStream fis = new FileInputStream(fisa); 
     ZipEntry zipEntry = new ZipEntry(fisa.getName()); 
     zos.putNextEntry(zipEntry); 

     byte[] bytes = new byte[1024]; 
     int length; 
     while ((length = fis.read(bytes)) >= 0) { 
      zos.write(bytes, 0, length); 
     } 

     zos.closeEntry(); 
     fis.close(); 
    }