阅读文章

Java中调用外部命令

[日期:2005-10-31] 来源:未知  作者:佚名 [字体: ]

Java中调用外部命令

public class ExecCommond{

public ExecCommond(){}

/**

* 执行一条命令

* @param execStr String 命令字符串

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

*/

public static String exec(String execStr) {

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

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

try {

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

//执行windows下的命令

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

Process proc = runtime.exec(args); //启动另一个进程来执行命令

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

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

String line = "";

while ( (line = br.readLine())

!= null) {

outInfo = outInfo + line + "\n";

System.out.println(outInfo);

}

// 检查命令是否失败。



try {

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

System.err.println("exit value = " +

proc.exitValue());

}

}

catch (InterruptedException e) {

System.err.print(e);

e.printStackTrace();

}

}

catch (IOException e) {

flag = false;

System.out.println("exec error: " + e.getMessage());

e.printStackTrace();

}

finally {

return outInfo;

}

}

}





阅读:
录入:

评论 】 【 推荐 】 【 打印
上一篇:java的io简单应用 选择自 FrankTaylor 的 Blog
下一篇:java中Properties类的使用
相关文章      
本文评论
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款