0

I am trying to expand a zip file using 7zip but I keep getting the 7zip Usage printout.

The zip exist in c:\temp

The same command succeed in batch window :

C:\TEMP>7z x "tryThis.zip"

I tried adding the workdir path to the file,And also without the working dir, nothing help. - I can probably run this using CMD/c command but I prefer to keep the code clean

What am I doing wrong?

Thank you!

String  pathTo7ZipExe = "c:\\program files\\7-zip\\7z.exe";
String fileName ="tryThis.zip";
String workingDir = "c:\\temp\\";

Process process = Runtime.getRuntime().exec(
                                     new String[]{pathTo7ZipExe},
                                     new String[]{" x \"" + fileName +"\""},
                                     new File(workingDir)); 

BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));  
String line;  
while ((line = in.readLine()) != null) {  
      System.out.println(line);  
}  
// wait for zip to end.
int exitVal = process.waitFor();  
azro
  • 53,056
  • 7
  • 34
  • 70
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159

2 Answers2

6

Please have a look at the documention for Runtime.exec

What you were actually trying to do is calling 7-zip without arguments and providing the arguments as your environment. Environment is something like Windows PATH etc.

so you would probably want to do something like:

Runtime.getRuntime().exec(new String[]{pathToZipExe, "x", fileName}, null, new File(workingDir));

On the other hand I would strongly advise to have a look on ZipInputStream which is included in java - using that you can also unpack zip files.

Cheers

michael_s
  • 2,515
  • 18
  • 24
  • Great! - btw [this](http://www.kodejava.org/examples/334.html) would be a solution with the java's ZipInputStream. One advantage is, that you can specifically look for elements, without unpacking the whole archive. – michael_s Feb 15 '13 at 22:25
1

You're invoking the overload of exec which accepts envp array as the second argument. This envp array is not for arguments at all, so actually you don't pass any arguments: that's why you get the usage printout.

Quotes and spaces aren't themselves part of arguments: they are used for separation into argv (with minor reservations, it's also true for Windows: that's how CommandLineToArgW works, even though full original command line with quotes and spaces is always available).

So it should be something like this:

Runtime.getRuntime().exec(new String[]{pathTo7ZipExe, "x", fileName},
                  new String[]{}, new File(workingDir));

(too bad I don't know Java, so the code might be unidiomatic, but it should work).

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • one small problem with the environment: null would inherit the original environment, new `String[]{}` would yield an empty environment (no PATH etc. set) - not sure if that is what is wanted. – michael_s Feb 15 '13 at 22:12