且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CreateProcess error=2, 系统找不到指定的文件

更新时间:2023-01-25 23:26:32

假设 winrar.exePATH 中,则 Runtime.exec 能够找到它,如果没有,您将需要提供它的完全限定路径,例如,假设 winrar.exe 安装在 C:/Program Files/WinRAR 你需要使用类似...

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

就我个人而言,我建议您使用 ProcessBuilder,因为它具有除其他外的一些额外配置功能.在可能的情况下,您还应该将命令和参数分成单独的 String 元素,它比单个 String 变量更好地处理诸如空格之类的事情,例如...

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

不要忘记从进程中读取InputStream的内容,否则可能会导致进程停止

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