简体   繁体   中英

Expanding files with 7zip

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();  

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM