0

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();
                }
         }
   }
Jayan
  • 18,003
  • 15
  • 89
  • 143
user3436156
  • 103
  • 1
  • 2
  • 11
  • Is it some homework question. why not use Java APIs to create files/directories... – Jayan Mar 19 '14 at 06:35
  • @Jayan is correct. It suits well for other OS also. Better use java api's. – Shriram Mar 19 '14 at 06:37
  • possible duplicate of [Using redirection operators with Java Runtime Exec](http://stackoverflow.com/questions/12380054/using-redirection-operators-with-java-runtime-exec) – Michał Politowski Mar 19 '14 at 08:19

1 Answers1

1

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.

morgano
  • 17,210
  • 10
  • 45
  • 56