java 如何调用 exe 文件 运行cmd命令

java 如何调用 exe 文件

每个 Java 应用程序都有一个 Runtime 类实例,使应用程序能够与其运行的环境相连接。可以通过 getRuntime 方法获取当前运行时。

应用程序不能创建自己的 Runtime 类实例。

1. static Runtime getRuntime()
返回与当前 Java 应用程序相关的运行时对象。
2. Process exec(String command)
在单独的进程中执行指定的字符串命令。

[code]
import java.io.IOException;

public class TestRT {

/**
* 使用Runtime对象的exec方法,调用外部exe文件。
*/
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
rt.exec("mspaint.exe");
rt.exec("D:\\Program Files\\Tencent\\QQ\\Bin\\QQ.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}

[/code]

运行cmd命令
[code]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;

public class TestRT {
public final static int END_MARK = 0;

/**
* 使用Runtime对象的exec方法,运行cmd命令。
*/
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec("ping www.hao123.com "); //运行cmd命令
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String s = br.readLine();
String temp = "" ;
while(null != s ){
if(!"".equals(s.trim())) temp = s;
System.out.println(s);
s = br.readLine();
}
br.close();
//导致当前线程等待,如果必要,一直要等到由该 Process 对象表示的进程已经终止。
pr.waitFor();
//此 Process 对象表示的子进程的出口值。根据惯例,值 0 表示正常终止。
if (END_MARK == pr.exitValue()) {
JOptionPane.showMessageDialog(null, temp );
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值