2012-09-26 72 views
1

可能重复:
How to use Pipe Symbol in Javalinux命令在Java应用程序没有运行

您好我想通过我的Java应用程序来运行一些Linux命令。当我运行下面的命令时,它既不会引发异常也不会提供输出。但是,当我从linux命令提示符运行时,它执行得当。当我通过java应用程序给出“ls -al”命令时,它正常工作。那么如何让它工作?

以下是命令。

String cmd = "dir | grep gpc | grep -v 25"; 

以下是我的java程序

public class Test { 

    public static void main(String[] args) { 





     //String cmd = "ls -al"; 





     String cmd ="dir | grep gpc | grep -v 25" ; 

     String property = System.getProperty("user.dir"); 
     System.out.println("current directory:::: "+property); 
     String cmd =property+File.separator+"test1.sh" ;*/ 

     //String cmd ="ls -al" ; 
     //String cmd = args[0]; 

     String cmd = dir | grep gpc | grep -v 25; 
     System.out.println("executing command is:: "+cmd); 
     //String cmd ="dir | grep gpc | grep -v 25" ; 
     Runtime run = Runtime.getRuntime(); 
     Process pr = null; 
     try { 
      pr = run.exec(cmd); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     try { 
      pr.waitFor(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     BufferedReader buf = new BufferedReader(new InputStreamReader(
       pr.getInputStream())); 
     String line = ""; 
     try { 
      while ((line = buf.readLine()) != null) { 

       System.out.println(line); 

      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 

} 

回答

0

我得到了答案。需要以下列方式给出答案。

String[] cmd = { 
"/bin/sh", 
"-c", 
"dir | grep gpc | grep -v 25" 
}; 

Process p = Runtime.getRuntime().exec(cmd); 
2

sh -c前面加上它应该解决您的问题。管道是一个外壳特征。