3
votes

I am writing a java program on windows platform. I need to compress certain files into a zip archive. I am using ProcessBuilder to start a new 7zip process:

ProcessBuilder processBuilder = new ProcessBuilder("7Z","a",zipPath,filePath);
Process p = processBuilder.start();
p.waitFor();

The problem is that the 7zip process never exits after completion. It does create the required zip file but after that just hangs in there. This means that the waitFor() call never returns and my program gets stuck. Please suggest a fix or a work around.

1
sometimes the problems with calling processes is that you need to process / clear the output the produce. once their output buffer is full, they wait for the buffer to come free again.. - bert
Did you know Java has a zip package to read/write zip files? java.sun.com/developer/technicalArticles/Programming/… - Jonathon Faust
Thank you that fixed it. I just redirected output to a file - user434541
@user434541: You can answer your own question. Just put your solution here and mark it as accepted solution. That way you will help others in finding a solution in future and cleaning up of SO pending question queue :). - Favonius

1 Answers

2
votes

here is what I ended up doing.

I can't set enviroment variables so I had to set the c: path for 7zip.

    public void zipMultipleFiles (List<file> Files, String destinationFile){
        String zipApplication = "\"C:\\Program Files\7Zip\7zip.exe\" a -t7z"; 
        String CommandToZip = zipApplication + " ";    
        for (File file : files){
           CommandToZip = CommandToZip + "\"" + file.getAbsolutePath() + "\" ";
        }
        CommandToZip = CommandToZip + " -mmt -mx5 -aoa";
        runCommand(CommandToZip);
    }

    public void runCommand(String commandToRun) throws RuntimeException{
        Process p = null;
        try{
            p = Runtime.getRuntime().exec(commandToRun);
            String response = convertStreamToStr(p.getInputStream());
            p.waitFor();
        } catch(Exception e){
            throw new RuntimeException("Illegal Command ZippingFile");
        } finally {
            if(p = null){
                throw new RuntimeException("Illegal Command Zipping File");
            }
            if (p.exitValue() != 0){
                throw new Runtime("Failed to Zip File - unknown error");
            }
        }
    }

The convert to string function can be found here which is what I used as a reference. http://singztechmusings.wordpress.com/2011/06/21/getting-started-with-javas-processbuilder-a-sample-utility-class-to-interact-with-linux-from-java-program/