Trijit Trijit - 6 months ago 36
Java Question

CreateProcess error=2, The system cannot find the file specified

I am writing a program in java which would execute winrar and unzip a jar file for me placed in h:\myjar.jar into the folder h:\new. My java code goes something like this


public class MainClass {

public static void main(String[] args) {

Runtime r=Runtime.getRuntime();
Process p=null;

try {
File dir=new File("C:/Program Files/WinRAR");
p=r.exec("winrar x h:\\myjar.jar *.* h:\\new",null,dir);

} catch (IOException e) {
// TODO Auto-generated catch block



When i execute this, i am getting this error Cannot run program "winrar" (in directory "C:\Program Files\WinRAR"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at MainClass.main(
Caused by: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 4 more

Can anyone tell me why am i encountering such a problem. What is the change i need to incorporate in code so that it works..?


Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "new"); File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process