2013-02-24 100 views
0

命令我想通過一個Java程序運行命令運行Windows的Java程序

ipmsg.exe /味精192.168.0.8 「短信」

。有誰能夠幫助我?

我正在嘗試以下幾行。但它不起作用..

Runtime run_t = Runtime.getRuntime(); 

Process notify = run_t.exec("cmd /c ipmsg.exe /MSG 192.168.0.8 Hello"); 

PS: - 我的電腦連接到計算機與ip地址192.168.0.8與局域網。

+5

「它不工作」 是*永不*足夠的信息。與你預期發生的事情相比,發生了什麼?請閱讀http://tinyurl.com/so-list – 2013-02-24 09:55:10

+2

你是否從shell或CLI執行了這個命令,看看它是否真的用於Java? – asgs 2013-02-24 10:00:04

+0

其實我想發短信到與我的電腦連接的電腦上使用Lan。我正在使用IP Messenger工具。我想通過java程序來運行這個工具,因此我輸入命令 「ipmsg.exe/MSG ipaddress text_message」。但是,當我使用java程序時,此命令不起作用 – user2087814 2013-02-24 10:02:55

回答

2

使用ProcessBuilder更好地處理外部過程。另外,除命令名外,總是將參數作爲單獨的字符串傳遞。

+1

這不太可能解決問題。 – assylias 2013-02-24 10:02:03

+0

但ip地址不是字符串。那麼如何將它傳遞給exec()或ProcessBuilder? – user2087814 2013-02-24 10:14:24

+0

無論您作爲命令(包括命令名稱)的一部分提供的輸入都被視爲來自Java視角的字符串。 – asgs 2013-02-24 10:16:34

1

你需要兩個線程捕獲standal輸出或錯誤輸出是這樣的:

package demo; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 


public class ExecDemo { 

    public static void main(String[] args) throws Exception { 

     final Process p = Runtime.getRuntime().exec("nslookup google.com"); 
     Thread stdout = new Thread() { 
      public void run() { 
       BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
       String line = null; 
       try { 
        while ((line = br.readLine())!=null) { 
         System.out.println(line); 
        } 
        br.close(); 
       } catch (IOException ioe) { 
        ioe.printStackTrace(); 
       } 
      } 
     }; 
     Thread stderr = new Thread() { 
      public void run() { 
       BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); 
       String line = null; 
       try { 
        while ((line = br.readLine())!=null) { 
         System.out.println(line); 
        } 
        br.close(); 
       } catch (IOException ioe) { 
        ioe.printStackTrace(); 
       } 

      } 
     }; 
     // 
     stdout.start(); 
     stderr.start(); 
     // 
     stdout.join(); 
     stderr.join(); 
     // 
     p.waitFor(); 
    } 

} 

輸出(在Mac OS X):

Server:  192.168.6.1 
Address: 192.168.6.1#53 

Non-authoritative answer: 
Name: google.com 
Address: 74.125.31.113 
Name: google.com 
Address: 74.125.31.138 
Name: google.com 
Address: 74.125.31.139 
Name: google.com 
Address: 74.125.31.100 
Name: google.com 
Address: 74.125.31.101 
Name: google.com 
Address: 74.125.31.102 
+0

+1閱讀流程'溪流片段。 @ user2087814你可能需要嘗試類似這樣的事情,比如assylias暗示。 – asgs 2013-02-24 10:22:28

+0

謝謝大家的幫助..我的程序現在工作正常:) – user2087814 2013-02-24 11:51:17

+0

@ user2087814你可能想解釋你爲了讓程序工作而做了什麼,以便別人可以學習。 – asgs 2013-03-05 18:35:47