I need to grep some text inside a list of files(file count is huge) in unix server and then list the file name in a web gui. So I decided best way to achieve this is by writing a unix command executer using Runtime.getRuntime(). Works fine for most of the unix command but facing this strange grep issue.
First of all code:
public class UnixCommandExecutor {
private static StringBuffer output = new StringBuffer();
public static String exec(String command) throws Exception{
Process process = null;
process = Runtime.getRuntime().exec(command);
BufferedReader stdErr = getBufferedReader(process.getErrorStream());
BufferedReader stdIn = getBufferedReader(process.getInputStream());
StringBuffer data = extractData(stdErr);
if (data.length() >= 1) {
System.out.println("Error: " +data.toString());
throw new Exception(data.toString());
}
data = extractData(stdIn);
if (data.length() >= 1) {
output = data;
System.out.println("Output: " +data.toString());
}
return output.toString();
}
private static BufferedReader getBufferedReader(InputStream stream) {
InputStreamReader inReader = new InputStreamReader(stream);
BufferedReader buffReader = new BufferedReader(inReader);
return buffReader;
}
private static StringBuffer extractData(BufferedReader reader)
throws IOException {
StringBuffer data = new StringBuffer();
String s = "";
while ((s = reader.readLine()) != null) {
data.append(s + "\n");
}
return data;
}
public StringBuffer getOutput() {
return output;
}
}
Now the call would be something like this: String output = exec("find . -name blah"); This works fine and the result is perfect. Or any other unix command executes and provides the result properly.
But when grep command is used it gives a strange error: String output = exec("grep -l executor *");
Error: grep: *: No such file or directory
This is strange, since if I run this command directly on unix it gives the desired result. Also tried giving the file path something like, String output = exec("grep -l executor /file/path/*"); even then the error is:
Error: grep: /file/path/*: No such file or directory
Any ideas? or any other better way to solve this? Any suggestion is welcome.
/bin/sh -cand secondly useRuntime.exec(String[])api. So overall my method call now looks likeString[] commands = new String[]{"/bin/sh","-c","grep -l executor *"}; exec(commands);Works just fine and result is displayed