【问题标题】:How I run a console application from a java console?如何从 Java 控制台运行控制台应用程序?
【发布时间】:2013-02-11 05:03:56
【问题描述】:

我在搞乱 Runtime.getRuntime(),但我不认为它真的是我想要的。

我想要一些既有用户输入又有输出到标准输出的东西。基本上,我希望启动一个完整的单独程序。

格雷

【问题讨论】:

标签: java console runtime exec runtime.exec


【解决方案1】:

您可以使用ProcessBuilder.start() 方法创建的Process 并使用它的输入和输出流。

这是一个简单的例子:

public static void main(String[] args) throws Exception {
    String[] processArgs = new String[]{"ping","google.com"};
    Process process = new ProcessBuilder(processArgs).start();

    BufferedReader in = new BufferedReader(new InputStreamReader(
            //I'am using Win7 with PL encoding in console -> "CP852"
            process.getInputStream(), "CP852"));

    String line;
    while ((line = in.readLine()) != null)
        System.out.println(line);

    in.close();
    System.out.println("process ended");
}

【讨论】:

    【解决方案2】:

    这样做:

    Process process = Runtime.exec( "somecommand.exeorwhatever" );
    

    将运行一个完全独立的进程。然后你可以使用:

    InputStream in = process.getInputStream();
    InputStream err = process.getErrorStream();
    OutputStream out= process.getOutputStream();
    

    【讨论】:

      猜你喜欢
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多