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

Java调用系统执行程序(OS Command)

2005-02-28 17:01 597 查看
以下代码在windows2000上可以运新哦。
SayHi.exe为任意的一个执行程序。

public static void main(String args[]) {
String s = null;
// system command to run
String cmd = "cmd /c c:/SayHi.exe";
// set the working directory for the OS command processor
File workDir = new File("c://");

try {
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
int i = p.waitFor();
if (i == 0) {
BufferedReader stdInput =
new BufferedReader(
new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} else {
BufferedReader stdErr =
new BufferedReader(
new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdErr.readLine()) != null) {
System.out.println(s);
}

}
} catch (Exception e) {
System.out.println(e);
}
}


还有这样一段代码也可以

public class ExecuteCommand{

public static void main(String[] args) throws Exception{
String[] cmd = {"sh","-c","clear"};
//String cmd = "clear";

Runtime rt = Runtime.getRuntime();
rt.exec(cmd);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息