Search code examples
javaprocessbuilder7zip

ProcessBuilder in Java


I´m studing about this subject in this page, but I can´t find the solution, how can I execute programs in cmd using ProcessBuilder? I want to compress, open, delete a file with 7zip using the command line. I have this code as example, but doesn´t work, cmd starts but doesn´t create the compress file:

String[] commands=
   {"cmd.exe", "7za", "a", "-t7z", "test.7z", "Test.txt", "/C", "start"};
ProcessBuilder pb = new ProcessBuilder(commands); 

Solution

  • The problem is a little bit in Java (start() missing), a little bit in 7za (command line garbled)

    new ProcessBuilder("7za", "a", "-t7z", "test.7z", "Test.txt").start();
    

    This command works only if 7za is in your PATH...

    If not you have to specify its path, under Windows:

    new ProcessBuilder(
       "C:/Program Files/7-Zip/7za.exe", "a", "-t7z", "test.7z", "Test.txt").start();
    

    Seven zip help:

    7-Zip (A) 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
    
    Usage: 7za <command> [<switches>...] <archive_name> [<file_names>...]
           [<@listfiles...>]
    
    <Commands>
      a: Add files to archive
      ...
    <Switches>
      ...
      -t{Type}: Set type of archive