【问题标题】:Writing the Output of an Operating System Command to the Console将操作系统命令的输出写入控制台
【发布时间】:2012-06-11 12:23:14
【问题描述】:

我想在 Java 中执行一个操作系统命令,然后打印出它的返回值。像这样:

这就是我正在尝试的......

String location_of_my_exe_and_some_parameters = "c:\\blabla.exe /hello -hi";
Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);

我尝试将 System.out.print() 放在 Runtime... 行的开头,但失败了。因为,显然,getRuntime() returns a Runtime object

现在,问题是,当我在命令行中执行“blabla.exe /hello -hi”命令时,我得到的结果类似于:“你执行了一些命令,万岁!”。但是,在 Java 中,我一无所获。

我尝试将返回值放入 Runtime 对象,放入 Object 对象。然而,他们都失败了。我怎样才能做到这一点?

问题已解决 - 这是我的解决方案

Process process = new ProcessBuilder(location, args).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

while ((line = br.readLine()) != null) {
    System.out.println(line);
}

【问题讨论】:

    标签: java command-line command runtime executable


    【解决方案1】:

    注意Runtime.exec(...) 返回一个Process 对象。您可以使用此对象来捕获其输入流并检索它打印到标准输出的任何内容:

    Process p = Runtime.getRuntime().exec(location_of_my_exe_and_some_parameters);
    InputStream is = p.getInputStream();
    
    // read process output from is
    

    【讨论】:

    • 非常感谢。感谢您的友善、礼貌和快速。
    • @John Doe:确保将对您最有帮助的答案标记为已接受,以便未来的读者快速找到它。
    • 我想我不能标记或投票。我没有足够的“业力”。
    • @John Doe:你需要 15 分才能投票,但你可以在任何分数上标记,甚至是 1。
    【解决方案2】:

    您可以使用以下命令捕获命令的输出:

     Runtime rt = Runtime.getRuntime();
     Process pr = rt.exec(command);
     BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
     String line=null;
    
     while((line=input.readLine()) != null) {
        log.info(line);
     }
      //This will wait for the return code of the process
     int exitVal = pr.waitFor();
    

    【讨论】:

      【解决方案3】:

      使用ProcessBuilder 而不是运行时。

      喜欢:

      Process process = new ProcessBuilder("c:\\blabla.exe","param1","param2").start();

      答案:

      Process process = new ProcessBuilder("c:\\blabla.exe","/hello","-hi").start();
      InputStream is = process.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line;
      
      System.out.printf("Output of running %s is:", Arrays.toString(args));
      

      【讨论】:

        猜你喜欢
        • 2017-12-21
        • 1970-01-01
        • 1970-01-01
        • 2014-07-18
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多