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();
                }
         }
   }
3
  • Is it some homework question. why not use Java APIs to create files/directories... Commented Mar 19, 2014 at 6:35
  • @Jayan is correct. It suits well for other OS also. Better use java api's. Commented Mar 19, 2014 at 6:37
  • possible duplicate of Using redirection operators with Java Runtime Exec Commented Mar 19, 2014 at 8:19

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.