2014-04-02 36 views
1
的输出

说我有这样的功能:检索的ProcessBuilder

public String runCommand(parameters, boolean interactive) 
{ 
    Process p = null; 

    // some code 

    try 
    { 
     final ProcessBuilder pb = new ProcessBuilder(my_command); 
     pb.inheritIO(); // So the output is displayed on the console 
     p = pb.start(); 
     p.waitFor(); 
    } 
    catch(IOException | InterruptedException e) 
    { 
     e.printStackTrace(); 
    } 

    if (interactive) 
    { 
     return p.exitValue() + ""; 
    } 
    else 
    { 
     // return the stdout of the process p 
    } 
} 

我想要做的就是回到我通过ProcessBuilder运行的进程的标准输出,只有在interactive布尔设置为false。但是,我无法确定如何将标准输出重定向到ProcessBuilder的变量。请不要使用inheritIO(),所以当我使用像adb shell这样的函数时,shell会显示在我的控制台中,这是我想要的行为。所以基本上,至于现在,我可以看到在控制台的标准输出,但我不知道如何在函数中返回它,所以我可以使用这个值作为未来的东西的变量。

回答

0

试试这个

Process p = new ProcessBuilder(cmd).start(); 
    Reader rdr = new InputStreamReader(p.getInputStream()); 
    StringBuilder sb = new StringBuilder(); 
    for(int i; (i = rdr.read()) !=-1;) { 
     sb.append((char)i); 
    } 
    String var = sb.toString(); 
0

你可以做的是获得输出和当执行,就像这样:

pb.redirectErrorStream(true); 

    Process p; 
    try { 
     p = pb.start(); 

     BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line; 
     String output = ""; 
     while((line = in.readLine()) != null) { 
      log.info(line); 
      output += line + "\n"; 
     } 
     return output; 
    } catch (IOException e) { 
     // ... 
    } 
    return null;