无法从Runtime.getRunTime.exec()获取getInputStream

时间:2013-06-11 07:06:53

标签: java process runtime.exec

public class LinuxInteractor {

public static String executeCommand(String command)
{
System.out.println("Linux command: " + command);

try 
{
   Process  p = Runtime.getRuntime().exec(command);
   p.waitFor();
   BufferedReader bf=new BufferedReader(new InputStreamReader( p.getInputStream()));
   String str=bf.readLine();
   System.out.println("inputStream is::"+str);
   while( (str=bf.readLine()) != null)
   {
       System.out.println("input stream is::"+str);        
   }
   System.out.println("process started");
}
catch (Exception e) {
System.out.println("Error occured while executing Linux command. Error       Description: "
    + e.getMessage());
    e.printStackTrace();
}
}

当我通过控制台运行脚本时,它正在运行。但是通过Java程序InputStream(Str)即将null

我还可以使用其他方法吗?

2 个答案:

答案 0 :(得分:5)

<强>解决方案
您应该尝试在不同的线程上执行读取和执行。

更好的选择是使用 ProcessBuilder ,为您处理“脏”的工作。
try块中的代码可能如下所示:

/* Create the ProcessBuilder */
ProcessBuilder pb = new ProcessBuilder(commandArr);
pb.redirectErrorStream(true);

/* Start the process */
Process proc = pb.start();
System.out.println("Process started !");

/* Read the process's output */
String line;             
BufferedReader in = new BufferedReader(new InputStreamReader(
        proc.getInputStream()));             
while ((line = in.readLine()) != null) {
    System.out.println(line);
}

/* Clean-up */
proc.destroy();
System.out.println("Process ended !");

另请参阅此 short demo


问题原因
根据 Java Docs waitFor()

  

导致当前线程在必要时等待,直到此Process对象表示的进程终止。

因此,您尝试在终止后获取进程的输出流,因此null


(对不起,对答案进行了重大修改。)

答案 1 :(得分:1)

您需要在单独的线程中执行此操作:

Process process = Runtime.getRuntime().exec(command);
LogStreamReader lsr = new LogStreamReader(process.getInputStream());
Thread thread = new Thread(lsr, "LogStreamReader");
thread.start();


public class LogStreamReader implements Runnable {

    private BufferedReader reader;

    public LogStreamReader(InputStream is) {
        this.reader = new BufferedReader(new InputStreamReader(is));
    }

    public void run() {
        try {
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

然后你需要第二个线程来进行输入处理。你可能想像stdout一样处理stderr。