I want to execute the following command through Java code. Can any one suggest how can I execute it?
find ./path/ | grep "keyword" | grep -rnw -e "keyword"
I am trying in many way, but not getting proper output.
I want to execute the following command through Java code. Can any one suggest how can I execute it?
find ./path/ | grep "keyword" | grep -rnw -e "keyword"
I am trying in many way, but not getting proper output.
Runtime.getRuntime().exec()
is your friend here.
Guys are right that it is a duplication of few other questions but mostly this one: How to make pipes work with Runtime.exec()?
Printing out the response is covered better here: java runtime.getruntime() getting output from executing a command line program
It seems like you want to execute pipes through java code. I found using shell or bash the easiest. You could also explore org.apache.commons.exec
package if you can.
Here is how I would do it:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String argv[]) {
try {
String[] cmd = {
"/bin/sh",
"-c",
"find ./path/ | grep \"keyword\" | grep -rnw -e \"keyword\""
};
Process exec = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(exec.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
System.out.println("Standard output:\n");
String s;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
System.out.println("Error output:\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}