2015-09-18 44 views
0
Executor exec = new DefaultExecutor(); 
exec.setWorkingDirectory("/var/java/apache-tomcat-7.0.47/webapps/Telegram/tg") 
CommandLine cl = new CommandLine("bin/telegram-cli -k tg-server.pub -W -U root"); 
int exitvalue = exec.execute(cl); 

如何才能得到這個命令的輸出:在Java中使用Linux shell提示符下交互

exec.execute(cl); 

並運行其他相關命令的電報,CLI命令提示符例如contact_list,msg聯繫人「Hello world」;

+0

哪個庫您使用要做到這一點?它看起來不像內置類。 –

+0

我沒有使用任何庫,但是這個軟件安裝在我們的專用服務器上。我正在嘗試使用簡單的java技術來運行程序及其相關命令 – Ghayel

+0

您正在使用一個庫,這是一個重要的實現,因爲一旦您知道了正在使用的庫,就可以閱讀它的文檔以瞭解如何使用它。 https://commons.apache.org/proper/commons-exec/tutorial.html –

回答

0

它在我看來好像只是使用ProcessBuilder會更容易。

ProcessBuilder pb = new ProcessBuilder("bin/telegram-cli","-k","tg-server.pub","-W","-U","root"); 
pb.directory(new File("/var/java/apache-tomcat-7.0.47/webapps/Telegram/tg")); 
Process p = pb.start(); 
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()),true)) { 
    String line = null; 
    pw.println("contact_list"); 
    while ((line = br.readLine()) != null) { 
     System.out.println("line = " + line); 
    } 
} 

更新 它看起來像爲PrintWriter的寫入需要被刷新。您可以通過調用pw.flush()或將第二個參數true添加到PrintWriter構造函數來完成此操作。我不知道用於telegram-cli的命令,但是你需要添加一個可以產生輸出的命令來確定何時退出。這裏有一個使用/ bin/sh的例子。

ProcessBuilder pb = new ProcessBuilder("/bin/sh"); 
Process p = pb.start(); 
try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()),true)) { 
    String line = null; 
    pw.println("ls"); 
    pw.println("pwd"); 
    pw.println("echo quit"); // this gives me output I can test for to break the loop 
    pw.flush(); 
    while ((line = br.readLine()) != null && !line.contains("quit")) { 
     System.out.println("line = " + line); 
    } 
} 
int retcode = p.waitFor(); 
System.out.println("process ended with " + retcode); 

產生這樣的輸出:

line = build 
line = build.xml 
line = dist 
line = manifest.mf 
line = nbproject 
line = src 
line = /home/shackle/NetBeansProjects/JavaApplication20 
process ended with 0 
+0

line = Telegram-cli使用libpython 2.6版本。 6 線= I:配置目錄= [/根/ .telegram-CLI] 線=> 線=> 線=> 線=> 線=> 線=> 線=> 線=> line => line => line => line => line => 它的啓動無限循環 – Ghayel

+0

感謝我的心底。當bin/telegram-cli ...開始時如何使用其他命令contact_list或msg用戶msgtext? – Ghayel

+0

上面的代碼不執行pw.println(「contact_list」); – Ghayel