您的位置:首页 > 其它

JVM执行WINDOWS命令的方法

2008-11-05 10:30 232 查看
public class ExecCommand {

public ExecCommand() {

}

/**

* 执行一条命令

*

* @param execStr

* String 命令字符串

* @return String 执行命令错误时的信息。

*/

public void exec(String execStr) {

System.out.println("exec this function");

Runtime runtime = Runtime.getRuntime(); // 取得当前运行期对象

String outInfo = ""; // 执行错误的输出信息

// String[] args = new String[] { "sh", "-c", execStr };// 执行linux下的命令

// 执行windows下的命令

String[] args = new String[] {"cmd", "-c", execStr};

Process proc = null;

try {

proc = runtime.exec(args);

System.out.println("exec this function end");

InputStream in = proc.getErrorStream();// 得到错误信息输出。



if(in==null){

System.out.println("The executive result is null");

}



BufferedReader br = new BufferedReader(new InputStreamReader(in));

String line = "";

while ((line = br.readLine()) != null) {

outInfo = outInfo + line + "/n";

System.out.println("The executive result is null");

System.out.println(outInfo);

}

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} // 启动另一个进程来执行命令

// 检查命令是否失败。

try {



if (proc.waitFor() != 0) {

System.err.println("exit value = " + proc.exitValue());

System.out.println("exec this function end");

}

} catch (InterruptedException e) {

System.err.print(e);

e.printStackTrace();

}



}

/*

* ping the server

* @param server String

* @param timeout int

* @return boolean

* @throws IOException

*/

public boolean pingServer(String server,int timeout)

{

BufferedReader in = null;

Runtime r = Runtime.getRuntime();

String pingCommand = "ping " + server + " -w " + timeout;

try

{

Process p = r.exec(pingCommand);

if (p == null)

{

return false;

}

in = new BufferedReader(new InputStreamReader(p.

getInputStream()));

String line = null;

while ( (line = in.readLine()) != null)

{

System.out.println(line);

if (line.startsWith("Reply from"))

{

return true;

}

}

in.close();

}

catch (Exception ex)

{

return false;

}

return false;

}





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