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

前端 未结 5 853
既然无缘
既然无缘 2020-11-29 04:58

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

相关标签:
5条回答
  • 2020-11-29 04:59

    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",
        "x",
        "myjar.jar",
        "*.*",
        "new");
    pb.directory(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

    0 讨论(0)
  • 2020-11-29 05:02

    The complete first argument of exec is being interpreted as the executable. Use

    p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
                null, 
                dir);
    
    0 讨论(0)
  • 2020-11-29 05:03

    I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran

    ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
    pb.directory(new File("H:/"));
    pb. redirectErrorStream(true);
    
    Process p = pb.start();
    

    I got an error. But if I ran

    ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
    pb.directory(new File("H:/"));
    pb. redirectErrorStream(true);
    
    Process p = pb.start();
    

    everything was OK.

    0 讨论(0)
  • 2020-11-29 05:06

    My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

    Try

     p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);
    
    0 讨论(0)
  • 2020-11-29 05:25

    The dir you specified is a working directory of running process - it doesn't help to find executable. Use cmd /c winrar ... to run process looking for executable in PATH or try to use absolute path to winrar.

    0 讨论(0)
提交回复
热议问题