I am trying to execute a program from the Java code. Here is my code:
public static void main(String argv[]) {
try {
String line;
Process p =
To get the redirection to work as written, you need to do this:
Process p = Runtime.getRuntime().exec(
new String[]{"/bin/bash", "-c", "ls > OutputFileNames.txt"});
The problem you were running into is the simple-minded way that that Runtime.exec(String) splits a command line into arguments.
If you were to run that command (as is) at a shell prompt, you would have had to have entered it as:
$ /bin/bash -c "ls > OutputFileNames.txt"
because the "-c" option for "bash" requires the command line for the spawned shell as a single shell argument. But if you were to put the naked quotes into the Java String, the Runtime.exec(String) method still get the splitting wrong. The only solution is to provide the command arguments as an array.