java - 在 Java 中与命令行工具通信

标签 java linux process

我想在我的 Java 程序中使用 linux 命令行工具。我启动程序并使用 Process 类 ( http://download.oracle.com/javase/6/docs/api/java/lang/Process.html ) 获取输出:

 /* @param args
  * @throws IOException 
  */
 public static void main(String[] args) throws IOException {
    Process proc = Runtime.getRuntime().exec("octave");

    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader errorReader = 
        new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedWriter writer = 
        new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));

    int c;
    while((c = proc.getInputStream().read()) != -1) {
       System.out.print((char)c);
    }
    System.out.println("End");
 }

我得到以下输出:

GNU Octave, version 3.0.5 Copyright (C) 2008 John W. Eaton and others. This is free software; see the source code for copying conditions. There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'.

Octave was configured for "i486-pc-linux-gnu".

Additional information about Octave is available at http://www.octave.org.

Please contribute if you find this software useful. For more information, visit http://www.octave.org/help-wanted.html

Report bugs to (but first, please read http://www.octave.org/bugs.html to learn how to write a helpful report).

For information about changes from previous versions, type `news'.

奇怪的是,如果我在终端中运行 octave,正常输出如下:

:~/workspace/Console/src/c$ octave
GNU Octave, version 3.0.5 Copyright (C) 2008 John W. Eaton and others. This is free software; see the source code for copying conditions. There is ABSOLUTELY NO WARRANTY; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, type `warranty'.

Octave was configured for "i486-pc-linux-gnu".

Additional information about Octave is available at http://www.octave.org.

Please contribute if you find this software useful. For more information, visit http://www.octave.org/help-wanted.html

Report bugs to (but first, please read http://www.octave.org/bugs.html to learn how to write a helpful report).

For information about changes from previous versions, type `news'.

octave:1>

所以在我的输入流中没有发送请求输入的行中的字符。为什么?难道不能检测是否有输入请求吗?

感谢您的回答!

海因里希

最佳答案

*nix 上的程序可以检测它们是否正在与终端或其他流对话。并且许多交互式 shell 类型的程序基于此做出不同的 react (通过设置不同的提示,不读取一些 init 文件甚至根本不启动)。

您可能会遇到其中一种情况。

此外,也许使用 Java API 进行 Octave 可能是更简单的方法:joPAS ,例如。

关于java - 在 Java 中与命令行工具通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3554500/

相关文章:

java - 由于使用 java8 lambdas 时出现无效类型异常,Flink 无法运行我的应用程序

java - 我只想在客户端第一次连接时从多线程服务器发送一个字符串

linux - Docker 安装卷。没有权限

在Linux上用C创建可执行的加法程序

python - 为什么在 python 脚本完成之前不执行打印作业?

c# - 启动一个执行委托(delegate)的新进程

java - 为什么在 Spring 配置类中的 @Bean 方法上不需要 @Autowired?

java - 最小/最大值无故改变

mysql - 将命令输出重定向到 mysql

java - Linux 从 Java 控制台应用程序中杀死 Java 进程