2015-11-02 69 views
4

我需要从我的Java应用程序运行命令并处理它的输出。 的代码是这个样子:从Java执行本地OS命令时没有输出

public static void readAllOutput(){ 
     try { 
      final String cmd = new String("find ~ -iname \"screen*\""); 
      System.out.println(cmd); 
      Process ps = Runtime.getRuntime().exec(cmd); 
//   ps.waitFor(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(ps.getInputStream())); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       System.out.println(line); 
      } 
     } catch (IOException /*| InterruptedException*/ e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

当我执行该命令从OS我有一个大的输出,但在我的Java应用程序的输出是emty。

+2

我在想''''(user dir)是不是最好用'System.getProperty(“user.home”)填充''。另外** ProcessBuilder **是一个实用程序类,简化了处理。同时通过在同一时间读取错误流来循环。 –

+1

请重构您的代码ProcessBuilder – Jayan

+3

〜,*等由Shell扩展。你的过程(找到...)不会这样做。另一种方法是将bash -c 视为子进程 – Jayan

回答

2

你需要使用

getRuntime().exec(new String[] { "find", "~", "-iname","screen*"}); 

,或者尝试

getRuntime().exec(new String[] { "find", "~", "-iname","\"screen*\""}); 

序接受参数作为双引号。