我正在尝试通过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本地主机-U postgres -d postgres -c "vacuum verbose“
有没有人知道上面的程序到底出了什么问题?
发布于 2012-03-19 22:17:33
调用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代码的输入。然后,您可以像读取任何其他流一样读取它,并在您认为合适的时候将其显示给用户。
发布于 2012-03-19 22:09:49
您将cmd.exe /c start作为单个参数传递,因此它查找名为cmd.exe /c start的文件,但失败了。
而是将cmd1拆分为两个字符串:cmd.exe和/c start
https://stackoverflow.com/questions/9771548
复制相似问题