在Java中与linux shell提示符进行交互

时间:2015-09-18 19:34:25

标签: java linux

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);

如何输出此命令:

exec.execute(cl);

并在telegram-cli命令提示符上运行其他相关命令,例如contact_list,msg contact" Hello world";

1 个答案:

答案 0 :(得分: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