简体   繁体   English

用Java创建Unix文件

[英]unix file creation with java

If I use this command inside unix shell : 如果我在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 . 但是,当我将该命令放入Java程序中时,它不起作用,它不会给出任何错误,但是在程序执行完成后,不会创建任何文件

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. 在Unix中,您需要知道命令行首先由shell处理,然后执行结果字符串。 In your case, this command: ls -lrt > ttrr has a > in it that must be processed by a shell. 在您的情况下,此命令: ls -lrt > ttrr有一个> ,必须由Shell处理。

When you use Runtime.getRuntime().exec(command); 当您使用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. Shell不处理该command字符串,而是直接将其发送到OS以使其执行。

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. 如果要使命令正确执行(我说的是ls -lrt > ttrr ),则必须在同一命令中执行shell。 in the case of Bash you can use something like this: 在Bash的情况下,您可以使用以下方式:

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. 真正执行的命令是带有两个参数的命令:“ bash”(shell程序),“-c”是在命令行中执行脚本的Bash选项,而“ ls -lrt> ttrr”是实际的“命令”来运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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