1

Possible Duplicate:
How to use Pipe Symbol in Java

Hi I wanted to run some linux command through my Java application. When I run the below command neither it throws the exception nor gives the output.But that particular command when I run from the linux command prompt, it executed properly.Also when I gave "ls -al" command through java application it worked properly. So how to make it work?

Following is the command.

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

Following is my java program

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();
        }

    }

}
Community
  • 1
  • 1
user414967
  • 5,225
  • 10
  • 40
  • 61

2 Answers2

2

Prepending it with sh -c should solve your problem. Pipes are a shell feature.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
0

I got the Answer .Need to give in the following way.

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

Process p = Runtime.getRuntime().exec(cmd);
user414967
  • 5,225
  • 10
  • 40
  • 61