2014-04-07 32 views
2

嗯,我正在生成2個.xml文件,但我想將它們保存在一個文件夾中,同時也壓縮它們,我不想生成它們分開,但在文件夾中分開並壓縮。 d 你明白了嗎?如何壓縮在代碼中生成的文件(Java)

我想把我要創建的兩個文件放入一個文件夾並壓縮它。我唯一想保存的是zip文件。

String name = fields.find(chooser.getLocation(), "mimic"); 
       Mimic mimic = getMimic(mimicList.get(0)); 
       String fileName = chooser.getSelectedFile().toString() + File.separator + "des_" +nombreMimic.substring(0, nombreMimic.length()-4)+ ".xml"; 
       String config = chooser.getSelectedFile().toString() + File.separator + "cfg_" +nombreMimic.substring(0, nombreMimic.length()-4)+".xml"; 
       FileOutputStream file; 
       FileOutputStream file2; 


       file = new FileOutputStream(fileName); 
       file2 =new FileOutputStream(config); 

       Parser parser; 
       parser = new Parser(file,new String[]{}); 
       parser.render(mimic , fields); 
       JOptionPane.showMessageDialog(null, "Complete!"); 

       Parser2 parser2; 
       parser2 = new Parser2(file2,new String[]{}); 
       parser2.render(mimic , fields); 
       JOptionPane.showMessageDialog(null, "Complete!"); 


       FileInputStream inputStream = new FileInputStream(chooser.getSelectedFile().toString() + File.separator + "des_" +nombreMimic.substring(0, nombreMimic.length()-4)+ ".xml"); 
       ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(nombreMimic.substring(0, nombreMimic.length()-4)+".des")); 

       zip.putNextEntry(new ZipEntry(fileName)); 

       byte [] buffer = new byte [1024]; 
       int bytesRead; 
       while((bytesRead=inputStream.read(buffer))>0){ 

       zip.write(buffer,0,bytesRead); 

       } 

       zip.closeEntry(); 
       zip.close(); 
       inputStream.close(); 


      } catch (Exception ex) { 
       Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); 

       JOptionPane.showMessageDialog(null, "Error parsing"); 
      } 
     } 
    } 
}           
+0

您使用的是Java 7嗎? – fge

+0

沒有以前。更新不是一個選項,這將被整合到其他的東西 –

回答

1

它看起來像回答您的問題在這裏得到解答:how to zip a folder itself using java

在那裏,它解釋瞭如何使用Java來壓縮文件/文件夾。

你必須將文件保存爲這項工作的文件夾中,但一旦拉上,你可以刪除下面這個tutorial它採用原始文件夾:

String path = "/path/to/file"; 
Files.delete(path); 

這種方式唯一保存會是zip文件。

相關問題