简体   繁体   中英

interacting with linux shell prompt in Java

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

How can I get output of this command:

exec.execute(cl);

and run other related commands on telegram-cli command prompt eg contact_list, msg contact "Hello world";

It looks to me as though it would be easier just to use ProcessBuilder instead.

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

Update It looks like the writes with PrintWriter need to be flushed. You can do this by calling pw.flush() or adding the second argument true to the PrintWriter constructor. I don't know the commands for telegram-cli, but you need to add one that will produce an output you can use to identify when to quit. Here's an example using /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);

Produces this output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM