How to create zip file of directory using/in Java?

UPDATED: 19 February 2011
zip
Creating compressed zip using command line. I'm going to demonstrate creating zip using java based windows application.

JFileChooser open = new JFileChooser(); //File chooser
open.setCurrentDirectory(new java.io.File("."));
open.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Allow to select on directory
option = open.showOpenDialog(ch.getParent());
filename = open.getSelectedFile().toString(); // getting the selected directory path

System.out.println("folder" + filename);
path = filename.replace("\\", "\\\\"); // Replace single / with //
String current_dir_name = open.getSelectedFile().getName(); // getting the selected directory path

try {
      String[] command = new String[3];
      command[0] = "cmd";
      command[1] = "/c";
      command[2] = "zip -r c:\\" + current_dir_name + ".zip " + path;
      /*
       * c:\\current_dir_name.zip is output file
       * path is original dir path
       **/

      Process p = Runtime.getRuntime().exec(command); //it'll execute above array on command line
      /* Standard input reader */
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      /* Standard error reader */
      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String Error;

      while ((Error = stdError.readLine()) != null) {
          System.out.println(Error); // It'll print the error if any
      }

      filename = current_dir_name + ".zip";
      path = "c:\\" + filename;
} catch (Exception e) {
      e.printStackTrace();
}
Read further about executing multiple command using java program: How to execute multiple command in single line in/using Java?

0 comments :