它在我看來好像只是使用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
哪個庫您使用要做到這一點?它看起來不像內置類。 –
我沒有使用任何庫,但是這個軟件安裝在我們的專用服務器上。我正在嘗試使用簡單的java技術來運行程序及其相關命令 – Ghayel
您正在使用一個庫,這是一個重要的實現,因爲一旦您知道了正在使用的庫,就可以閱讀它的文檔以瞭解如何使用它。 https://commons.apache.org/proper/commons-exec/tutorial.html –