Reputation: 103
If I use this command inside unix shell :
ls -lrt > ttrr
I get my output.
But when I am putting that command inside a java program then it does not work, it does not give any error, but no file is created after the program execution is complete.
here is my program :
public class sam
{
public static void main(String args[])
{
try
{
Runtime.getRuntime().exec(" ls -lrt > ttrr");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Upvotes: 0
Views: 95
Reputation: 17422
In Unix you need to be aware that the command line is first processed by the shell and then the resulting string being executed. In your case, this command: ls -lrt > ttrr
has a >
in it that must be processed by a shell.
When you use Runtime.getRuntime().exec(command);
the command
string is not processed by a shell and is sent straight to the OS for it to be executed.
If you want your command to be executed properly (I'm talking about ls -lrt > ttrr
) you have to execute the shell in the same command. in the case of Bash you can use something like this:
public static void main(String args[]) {
try {
Runtime.getRuntime().exec(new String[] {"bash", "-c", "ls -lrt > ttrr"});
} catch(Exception e) {
e.printStackTrace();
}
}
what is really being executed is a command with two arguments: "bash" (the shell program), "-c" a Bash option to execute a script in the command line, and "ls -lrt > ttrr" which is the actual "command" you want to run.
Upvotes: 1