gpt4 book ai didi

java - 可能原因 java.io.IOException : CreateProcess error=2, 系统找不到指定的文件

转载 作者:行者123 更新时间:2023-12-01 15:29:08 25 4
gpt4 key购买 nike

我正在尝试通过 java 执行“VACUUM VERBOSE”命令。这是我的代码

public void executeCommand()
{
String cmd1= "cmd.exe /c start";
String location="C:\\PROGRA~1\\PostgreSQL\\8.3\\bin\\";
String postgresCommand="psql -h localhost -U postgres -d postgres";
String autoVaccum="-c \"vacuum verbose\"";
String []actualCmd={cmd1,location,postgresCommand,autoVaccum};

Process process=null;
try {
process = Runtime.getRuntime().exec(actualCmd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


public static void main(String[] args) {
MyTest test= new MyTest();
test.executeCommand();

}

但是我遇到了以下异常

java.io.IOException: Cannot run program "cmd.exe /c start": 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 MyTest.executeCommand(MyTest.java:36)
at MyTest.main(MyTest.java:48)
Caused by: java.io.IOException: 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)
... 5 more

当我直接在“开始”->“运行”窗口中直接键入上述字符串时,它会成功执行例如。cmd.exe/C start C:\PROGRA~1/PostgreSQL/8.3/bin/psql -h localhost -U postgres -d postgres -c "vacuum verbose"

有人能知道上面的程序到底出了什么问题吗?

最佳答案

有多种方法可以调用 exec()。您正在使用的 on 以 String[] 作为参数,期望每个标记位于数组的不同部分。所以呼吁

Runtime.getRuntime().exec("cmd /c start executable arg1 arg2");

当使用数组而不是一个字符串调用时,称为

Process p = Runtime.getRuntime().exec(new String[]{"cmd","/c","start","executable","arg1","arg2");    
BufferedReader inReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter outWriter = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

exec() 返回一个 Process 对象,然后您可以使用 getInputStream() 获取该对象的输出。这实际上是该过程的输出,它是 java 代码的输入。然后,您可以像任何其他流一样读取它,并根据需要将其显示给用户。

关于java - 可能原因 java.io.IOException : CreateProcess error=2, 系统找不到指定的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9771548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com