How do I call a CMD compressed file in Java

  • 2020-04-01 02:11:32
  • OfStack

Today, I encountered a strange problem while making a Java call to the Windows compression command. The code is as follows:

String cmd ="C:/Program Files (x86)/WinRAR/rar.exe a c:/test.rar c:/test.log";

//System.out.println(cmd);
Process proc = Runtime.getRuntime().exec(cmd);

The above code in Xp, win7, Windows server2003 to perform completely normal found after the code transferred to Windows Server2008, directly prompt Java exception.
After a two-hour study, the above code is modified as follows:

String[] cmd ={"C:/Program Files (x86)/WinRAR/rar.exe", "a","C:/test.rar" ,"c:/test.log"};

//System.out.println(cmd);
Process proc = Runtime.getRuntime().exec(cmd);

It's normal. This also has the advantage of resolving the problem of whitespace in the file path

Related articles: