2013-02-06 57 views
0

我试图做到这一点运行脚本管道与Java

echo "ls|head -3"|/bin/sh 
在Java中

重要的一点是,我想立即创建脚本字符串并使用该脚本运行shell进程并捕获脚本stdout。

上面的代码不工作并挂起,可能在输入流。

 Process p = Runtime.getRuntime().exec("/bin/sh"); 

     final OutputStream out = p.getOutputStream(); 
     final BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 

     final String cmd = "ls|head -3"; 

     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        out.write(cmd.getBytes()); 
        out.flush(); 
       } catch (IOException ex) { 
       } 
      } 
     }).start(); 


     final List list = new ArrayList(); 

     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        String line; 
        while ((line = in.readLine()) != null) { 
         list.add(line); 
        } 
       } catch (IOException ex) { 
       } 
      } 
     }).start(); 

     System.err.println("running ..."); 
     p.waitFor(); 

     System.err.println(list); 

    } 
+0

而是读利用现有> 0在您的测试读取条件 – twillouer

回答

0

在输入流上会有数据之前,需要关闭输出流。关闭输出流,向进程证实不会有进一步的输入。只有这样它才会开始处理并输出到您的输入流。

尝试增加您的第一个主题下面的代码,您的通话后,“刷新”:

out.close();