简体   繁体   中英

unix file creation with java

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();
                }
         }
   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM