通过Java控制命令行程序会话

时间:2014-07-12 14:25:37

标签: java

我有一个计算机代数程序(称为Reduce),它以交互方式在shell中工作:在shell中启动Reduce,然后你可以定义变量,计算这个和那个,以及什么不是。 Reduce将输出打印到shell中。我的想法是,我想为这个基于文本的程序构建一个前端,该程序评估其输出并将其转换为一个漂亮的LaTeX样式公式。为此,我想使用Java。

我可以通过exec()开始Reduce。但是我如何模拟打开的shell的文本输入,以及如何读回Reduce写入shell的内容?

由于 延

编辑1:当前代码

// get the shell
Runtime rt = Runtime.getRuntime();

// execute reduce
String[] commands = {"D:/Programme/Reduce/reduce.com", "", ""};
Process proc = null;
try {
    proc = rt.exec(commands);
} catch (Exception e) {
    System.out.println("Error!\n");
}

// get the associated input / output / error streams
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedWriter stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
try {
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
} catch (Exception e) {
}

// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
try {
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
} catch (Exception e) {
}

3 个答案:

答案 0 :(得分:1)

您需要获取与进程关联的流,包括InputStream,OutputStream和ErrorStream。然后,您可以通过OutputStream将消息发送到进程,然后通过InputStream和ErrorStream从进程中读取信息。

从我的一些代码:

  final ProcessBuilder pBuilder = new ProcessBuilder(TEST_PROCESS_ARRAY);

  final Process proc = pBuilder.start();

  procInputStream = proc.getInputStream();
  errorStream = proc.getErrorStream();

  errorSBuffer = new StringBuffer();
  streamGobblerSb = new StreamGobblerSb(errorStream, "Autoit Error", errorSBuffer);
  new Thread(streamGobblerSb).start();

  final Scanner scan = new Scanner(procInputStream);

答案 1 :(得分:0)

您可能希望了解如何使用Process类。

http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html

我相信您可以启动该过程,然后使用getOutputStream()将命令提供给该过程。

答案 2 :(得分:-1)

虽然这不是一个严格的答案,但我发现使用PHP的函数proc_open()更方便。这样我就可以直接在前端包含输出,而不必担心我的Java程序和html前端之间的通信。

对于每个想要坚持使用Java方法的人:文章http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html是一个很好的参考。