星期一, 1 二月 2010

UNIX 中JAVA执行命令

« 关于eclipse中使用hibernate的数据库名及表所有者的问题 | Main | Derby 数据库的两种布置方式 »
在使用java编写程序时候,我们可能需要执行shell命令,怎么办呢?看下面的例子:

import java.io.IOException;

public class ExecDemo {

        static void doExec1() throws IOException {

                // use pipes and I/O redirection
                // but without using a shell

                Runtime runtime = Runtime.getRuntime();
                runtime.exec("ls | wc >out1");
        }

        static void doExec2() throws IOException {

                // invoke a shell and give command to it

                Runtime runtime = Runtime.getRuntime();
                String[] args =
                        new String[]{"sh", "-c", "ls | wc >out2"};

                Process p = runtime.exec(args);
        }

        public static void main(String[] args) throws IOException {
                doExec1();
                doExec2();
        }
}

doExec1()不会正常执行,doExec2()可以正常执行。下面原文节选:

The problem with doExec1 is that Runtime.exec invokes actual executable binary programs. Syntax such as | and > are part of a particular command processor, and are only understood by that processor. ls is executed, but the rest of the shell command is not. However, doExec2 succeeds because it invokes a command processor or shell (sh), and gives the shell the input containing the | and > characters. Note that Runtime.exec could have been invoked with a single string argument like this:

    "sh -c 'ls | wc >out2'"

Posted by xiaojf at 7:30 下午 in 未分类

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« First  « Prev   1 2 3 4 5   Next »  Last »
« 二月 »
星期日星期一星期二星期三星期四星期五星期六
 123456
78910111213
14151617181920
21222324252627
28