I am getting an exception like java.io.IOException: Cannot run program cat /home/talha/* | grep -c TEXT_TO_SEARCH": error=2, No such file or directory while executing the command below despite that there are no issues when I execute the same command through the terminal. I need to execute and return the output of the command below:
cat /home/talha/* | grep -c TEXT_TO_SEARCH
Here is the method used to execute commands using Runtime class:
public static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
cat&grepcommands.$PATHis defined so it knows to look forcatalong/usr/bin:/sbin:/usr/sbin:/usr/local/binwhatever. Within the context of the Java Runtime, it does not have that environment./bin/bash); it passes the command directly to the operating system. This means wildcards like*and pipes (|) will not be understood, sincecat(like all Unix commands) does not do any parsing of those characters. You need to use something likep = new ProcessBuilder("bash", "-c", command).start();, or, if for some bizarre reason you need to stick to using the obsolete Runtime.exec methods,p = Runtime.getRuntime().exec(new String[] { "bash", "-c", command });.