2012-03-19 360 views
0

我试图通过java执行'VACUUM VERBOSE'命令。 这里是我的代码可能的原因java.io.IOException:CreateProcess error = 2,系统找不到指定的文件

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”

有人可以知道上面的程序究竟出了什么问题?

回答

0

您将cmd.exe /c start作为单个参数传递,因此它会查找名为cmd.exe /c start的文件并失败。

相反,分裂成cmd1两个字符串:cmd.exe/c start

1

有多种方式来调用exec()。你使用的是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代码中。然后,您可以像读取任何其他流一样读取它,并根据需要将其显示给用户。

+0

谢谢Thomas, 我在我的代码中做了一些修改。而不是字符串数组使用单个字符串,现在问题已解决 String actualCmd = cmd1 + location + postgresCommand + autoVaccum; 但是这个程序还没有打开命令行窗口,它显示了什么操作是由“VACUUM VERBOSE”命令执行的 但是当我使用这个程序执行其他命令时,它会打开命令行窗口 例如。 String cmd1 =“cmd.exe/c start dir”; 基本上我想向用户显示'vacuum command'的输出 – Abhi 2012-03-19 14:23:20

+0

查看从Process对象获取输出的更新。 – Thomas 2012-03-19 14:45:31

相关问题