2012-08-29 39 views
1

我在使用Java中的ProcessBuilder運行vmrun時遇到了很多困難。錯誤:無法打開虛擬機:「[datastore] myVM1/myVM1.vmx」,未知文件後綴

我有一個命令字符串像這樣:

java -cp . RunTest 'vmrun -T esx -h https://10.123.236.123:443/sdk -u root -p password revertToSnapshot "[datastore] myVM1/myVM1.vmx" snapshot1' 

當你運行上面的vmrun命令(不帶Java),該命令執行成功。但是用Java,我收到了ff。錯誤:

Error: Cannot open VM: "[datastore] myVM1/myVM1.vmx", unknown file suffix 

下面的代碼是:

public static void main(String args[]) { 
     runProcessBuilderMulti(args[0]); 
    } 

    static void runProcessBuilderMulti (String cmd){ 
     List<String> list = new ArrayList<String>(); 
     System.out.println("Running Command: "+cmd.replace("\"","\\\"")); 

     Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(cmd); 
     while (m.find()) 
       list.add(m.group(1)); 

     System.out.println(list); 

     try { 
       Process process = new ProcessBuilder(list).start(); 
       InputStream is = process.getInputStream(); 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader br = new BufferedReader(isr); 
       String line; 

       while ((line = br.readLine()) != null) { 
         System.out.println(line); 
       } 

       System.out.println(process.exitValue()); 
     } catch (Exception e) {} 
    } 

我使用的Runtime.exec()切換到的ProcessBuilder之前。我認爲這與引用有關,所以我添加了cmd.replace,但顯然這是一個不同的問題。

任何幫助,將不勝感激。謝謝!

回答

1

當我發現使用上述腳本的管道命令發生故障時,我正在使用ProcessBuilder。多一點谷歌搜索發現,ProcessBuilder需要打開一個shell來執行某些命令。

ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", "ls -l | grep daemon"); 

功能更新如下:

static void runProcessBuilderMulti (String cmd){ 

     System.out.println("Running Command: "+cmd.replace("\"","\\\"")); 

     try { 
       Process process = new ProcessBuilder("/bin/sh", "-c", cmd).start(); 
       InputStream is = process.getInputStream(); 
       InputStreamReader isr = new InputStreamReader(is); 
       BufferedReader br = new BufferedReader(isr); 
       String line; 

       while ((line = br.readLine()) != null) { 
         System.out.println(line); 
       } 

       System.out.println(process.exitValue()); 
     } catch (Exception e) {} 
    } 

我猜測,不再命令是比較難的過程,就像管道命令,所以它需要有自己的shell執行。

相關問題