您的位置:首页 > 编程语言 > Java开发

java程序执行外部命令

2015-07-14 19:03 591 查看
java程序执行外部命令

先来看一下java中运行外部命令(比如windows下的dos命令、linux下的shell命令)的方法:

Process proc = Runtime.getRuntime().exec(cmdstring);

其中cmdstring就是需要运行的外部命令。

注意:运行windows下的dos命令,不能直接exec(cmd),可以这样来调用:

cmdstring = "command.exe /c dir"; // 其中/c表示运行命令后关闭cmd窗口

Runtime.getRuntime().exec(cmdstring);

也可以将命令写到一个脚本文件中,然后执行该脚本文件。

如果命令有多个参数,可以用如下方法:

try {

        // Execute a command without arguments

        String command = "ls";

        Process child = Runtime.getRuntime().exec(command);

    

        // Execute a command with an argument

        command = "ls -al /tmp";

        child = Runtime.getRuntime().exec(command);

    } catch (IOException e) {

           //错误处理操作

   }

“If an argument contain spaces, it is necessary to use the overload that requires the command and its arguments to be supplied in an array ”


如果参数中有空格或特殊字符的,可以使用exec的重载形式,传入一个字符串的数组:





try {

        // Execute a command with an argument that contains a space

        String[] commands = new String[]{"grep", "hello world", "/tmp/f.txt"};

        commands = new String[]{"grep", "hello world", "c:\\Documents and Settings\\f.txt"};

        Process child = Runtime.getRuntime().exec(commands);

    } catch (IOException e) {

    }

接下来,我们看一下java调用linux shell脚本的方法:

首先,我们需要增加用户对该脚本的执行权限,即

String cmdstring = "chmod a+x test.sh";

Process proc = Runtime.getRuntime().exec(cmdstring);

proc.waitFor(); //阻塞,直到上述命令执行完

cmdstring = "bash test.sh"; //这里也可以是ksh等

proc = Runtime.getRuntime().exec(cmdstring);

//注意下面的操作

string ls_1;

BufferedReader   bufferedReader   =   new   BufferedReader(  new   InputStreamReader(proc.getInputStream());

while   (   (ls_1=bufferedReader.readLine())   !=   null);

bufferedReader.close();

proc.waitFor();

为什么要有上面那段操作呢?

原因是:可执行程序的输出可能会比较多,而运行窗口的输出缓冲区有限,会造成waitFor一直阻塞。

解决的办法是,利用Java提供的Process类提供的getInputStream,getErrorStream方法

让Java虚拟机截获被调用程序的标准输出、错误输出,在waitfor()命令之前读掉输出缓冲区中的内容。

 

windows下java调用批处理文件的方法同上,只不过少了改变执行权限的操作


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: