java程序执行外部命令

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调用批处理文件的方法同上,只不过少了改变执行权限的操作










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值