2013-12-12 54 views
1

我有一個函數來壓縮文件,另一個用來解壓。當我嘗試解壓我用我自己的函數生成的壓縮文件時,會出現空指針異常,因爲它找不到ZipEntry ...當我嘗試使用我的dezip函數對使用winzip製作的壓縮文件進行解壓縮時, 。ZipOutPutStream,ZipEntry的返回NULL,當我嘗試dezip

但是我可以打開並解壓縮由我使用WinZip程序生成的檔案,文件「內容」是在這裏,它的內容爲確定。只有當我使用我的dezip函數進行嘗試時纔會出現錯誤!

下面的代碼:

public static void zip() { 
     try { 
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 
      Document document = documentBuilder.newDocument(); 

      /* Code to create the xml */ 

      Properties outFormat = new Properties(); 
      /* properties */ 

      TransformerFactory factory = TransformerFactory.newInstance(); 
      Transformer transformer = factory.newTransformer(); 
      transformer.setOutputProperties(outFormat); 

      ByteArrayOutputStream output = new ByteArrayOutputStream(); 
      File file = new File("KOKO.zip"); 
      FileOutputStream foutput = new FileOutputStream(file); 

      DOMSource domSource = new DOMSource(document.getDocumentElement()); 
      StreamResult result = new StreamResult(output); 
      transformer.transform(domSource, result); 
      output.writeTo(foutput); 

      ZipOutputStream zos = new ZipOutputStream(foutput); 
      byte[] bytes = output.toByteArray(); 
      ZipEntry entry = new ZipEntry("content"); 
      zos.putNextEntry(entry); 
      zos.write(bytes); 
      zos.closeEntry(); 
      zos.close(); 

     /* here the catch clauses */ 
    } 

    public static void unzip(File zipfile, File folder) throws FileNotFoundException, IOException { 
     ZipInputStream zis = new ZipInputStream(new FileInputStream(zipfile)); 
     ZipEntry ze = null; 
     try { 
      ze = zis.getNextEntry(); 
      System.out.println("path :"+ zipfile.getAbsolutePath()); 
      File f = new File(folder.getAbsolutePath(), ze.getName()); 
      f.getParentFile().mkdirs(); 
      OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); 
      try { 
       try { 
        final byte[] buf = new byte[8192]; 
        int bytesRead; 
        while (-1 != (bytesRead = zis.read(buf))) 
         fos.write(buf, 0, bytesRead); 
       } finally { 
        fos.close(); 
       } 
      } catch (final IOException ioe) { 
       f.delete(); 
       throw ioe; 
      } 
     } finally { 
      zis.close(); 
     } 
    } 

感謝您的幫助

+0

你可以發佈整個堆棧跟蹤如果y我們的例外? – dARKpRINCE

回答

0

你開始通過ZipOutputStream zos

寫它,我想你應該刪除行之前,您寫這封信是您的zip文件foutput

output.writeTo(foutput); 
+0

是的,非常感謝你! – Skartt

相關問題