Java调用外部命令
来源:互联网 发布:手机淘宝安卓版 编辑:程序博客网 时间:2024/05/18 00:01
一、典型代码
public static void main(String[] args) { String cmd = "cmd /c echo hello world"; try { Process p = Runtime.getRuntime().exec(cmd); InputStream is = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while((line = br.readLine()) != null){ System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}
二、API分析
当Java需要调用外部命令时,在JDK里,唯一的方法便是使用Runtime类。Runtime有几个重载方法:public Process exec(String command); public Process exec(String [] cmdArray); public Process exec(String command, String [] envp); public Process exec(String [] cmdArray, String [] envp);
你可以传入如下参数给以上方法:
1、一个字符串,包括命令和命令参数,每个元素需要以空格隔开,就像dos或bash命令行输入一样。
2、一个字符串数组,也包括命令和命令参数
3、一个环境变量数组,以name=value的形式
返回Process抽象类,Process在不同的操作系统实现方式是不同的。
Process类负责处理Java与外部程序的输入输出。他有以下几个有用的方法:
1、getErrorStream()
获取子进程的错误流。
2、getInputStream()
获取子进程的输入流。
3、getOutputStream()
获取子进程的输出流。
4、waitFor()
导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。
5、exitValue()
返回子进程的出口值。
其中exitValue()这个方法执行时,如果此时外部程序没有结束,会抛出IllegalThreadStateException。如果你想获得执行结果,最好使用waitFor(),它会一直等待程序结束,返回结果。值0表示程序正常结束,其他值含义视具体而定。
三、与外部程序交互:
1、标准输入。有些外部命令需要你输入指令决定下一步的走向,你可以通过Process.getOutputStream()向外部程序写入数据。
2、标准输出和错误输出。
Process.getInputStream()可以得到外部程序的标准输出流。
Process.getErrorStream()可以得到外部程序的错误输出流。
需要注意的是,如果想既得到标准输出,又得到错误输出,要考虑它们与外部程序执行的异步性了。
InputStream stdInput = p.getInputStream(); BufferedReader br1 = new BufferedReader(stdInput); String line1 = null; while ( (line1 = br1.readLine()) != null) System.out.println(line1); InputStream errInput = p.getErrorStream(); BufferedReader br2 = new BufferedReader(errInput); String line2 = null; while ( (line2 = br2.readLine()) != null) System.out.println(line2);
正确用法:
Process p = Runtime.getRuntime().exec(cmd); InputStream stdInput = p.getInputStream(); //异步处理 copyInThread(stdInput); InputStream errInput = p.getErrorStream(); //异步处理 copyInThread(errInput); //异步处理方法 static void copyInThread(final InputStream is){ new Thread(){ public void run(){ try { BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; while((line = br.readLine()) != null){ System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); }
四、更详细内容来自(toolcloud)
- java调用外部命令
- java 调用外部命令
- Java调用外部命令
- Java如何调用外部外部命令?
- Java如何调用外部外部命令?
- Java中调用外部命令
- Java如何调用外部命令?
- Java中调用外部命令
- Java中调用外部命令
- Java中调用外部命令
- Java调用外部程序命令
- java中调用外部命令
- java调用外部命令卡死问题
- 标准java调用外部命令的写法
- php调用外部命令
- vc调用外部命令
- python调用外部命令
- Java 使用Runtime.getRuntime.exec 和 ProcessBuilder 调用外部命令
- 黑马程序员 数据库 函数依赖
- 开始iOS 7中自动布局教程(一)
- yii日历
- java中接口的定义与实现
- Mac OSX下破解软件的一般方法及过程
- Java调用外部命令
- 黑马程序员 Tansact——sql变量
- NSObject:类与协议
- Js打印页面指定内容
- 虚拟盘符注册表项修改项
- ubuntu下编译安装openocd配合JLINK调试
- 调用函数的方式决定了调用的上下文中的this值
- 划分树几道题目
- Myeclipse下安装Ext-js插件(亲测)