java Runtime.getRuntime()。exec无法获取某些命令的输出

时间:2014-04-10 21:08:59

标签: java linux macos bash terminal

我在OSX 10.8.5上并尝试从Java运行终端命令。

因此,使用下面的代码,我可以读取Runtime.getRuntime()。exec的输出,但不能读取其他命令。

你会看到一些命令返回它们的输出就像ls和ifconfig一样好,但是然后尝试让openssl返回它的输出要么不返回,要么挂起,具体取决于实现。

我还使用了两种不同的方法来读取输出,但两者的结果相同。

什么阻止某些命令返回任何输出?

    theCommand = "ls"; //this command works OK and returns its output

    //theCommand = "ifconfig"; //this command works OK and returns its output

    //theCommand = "openssl rand"; //this command does not return any output

    //theCommand = "/bin/sh openssl rand"; //this command does not return any output

    //theCommand = "/bin/sh -c openssl rand"; //this command hangs

    try {
      System.out.println("trying...");
      Process extProc=Runtime.getRuntime().exec(theCommand);
      extProc.waitFor();

      //READ ouput attempt #1 - this works okay for ls and ifconfig command
      //BufferedReader readProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
      //while(readProc.ready()) {
      //  theReadBuffer = readProc.readLine();
      //  System.out.println(theReadBuffer);
      //}

      //READ output attempt #2 - this works okay for ls and ifconfig command
      InputStream theInputStream = extProc.getInputStream();
      java.util.Scanner theScanner = new java.util.Scanner(theInputStream).useDelimiter("\\A");
      if (theScanner.hasNext()) {
          theReadBuffer = theScanner.next();
          System.out.println(theReadBuffer);
      }

    } catch( IOException e) {
      System.out.println(e.getMessage());
    } catch(InterruptedException e) {
      System.out.println(e.getMessage());
    }

我最终试图从这个命令生成随机字符(在终端中工作):

openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'

由于

1 个答案:

答案 0 :(得分:0)

好的,感谢Mark W对原始问题的评论,我意识到有些命令输出到stderr(使用getErrorStream),有些命令输出到stdout(使用getInputStream)。

所以做这样的事情可以让你阅读:

      BufferedReader readInputProc=new BufferedReader(new InputStreamReader(extProc.getInputStream()));
      while(readInputProc.ready()) {
        theReadBuffer = readInputProc.readLine();
        System.out.println(theReadBuffer);
      }
      BufferedReader readErrorProc=new BufferedReader(new InputStreamReader(extProc.getErrorStream()));
      while(readErrorProc.ready()) {
        theReadBuffer = readErrorProc.readLine();
        System.out.println(theReadBuffer);
      }