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

java调用.bat,.cmd或执行cmd命令并将输出结果显示的代码

2009-01-09 10:12 916 查看
<%@ page contentType="text/html; charset=utf-8" language="java" pageEncoding="utf-8"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.InputStreamReader"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="java.io.BufferedReader"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.io.IOException"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>执行命令</title>
</head>
<%
InputStream in = null;
InputStreamReader ir = null;
List list = new ArrayList();
String line = "";

String msg = "";
String batfile = request.getParameter("batfile");
if(batfile==null){batfile = "";}
if(!batfile.equals("")){
try {
Process p = Runtime.getRuntime().exec(batfile);
in = p.getInputStream();
ir = new InputStreamReader(in);
BufferedReader br = new BufferedReader(ir);
while ((line= br.readLine()) != null) {
list.add(line);
}
if (p.waitFor()!=0) {
msg = "批处理执行失败,请检查批处理文件是否正确!";
}
else
{
msg = "批处理执行成功!";
}
p.destroy();
Iterator it = list.iterator();
while (it.hasNext()) {
line = "";
line = line + (String)it.next();
}
it = null;
br.close();
br = null;
ir.close();
ir = null;
in.close();
in = null;
p.destroy();
p=null;
} catch (IOException e) {
msg = "io异常,请检查指定的批处理文件是否存在!";
}
catch (InterruptedException e) {
msg = "中断异常!";
}
catch (IllegalArgumentException e){
msg = "命令为空!";
}
catch(Exception e){
msg = "未知异常!";
}
}
else
{
msg = "请输入指令或者命令文件的路径!";
}

%>
<body>
<form name="form1" method="post" action="/fileupload/updatepro.jsp">
<table width="642" height="170" border="1" style="width: 936px">
<tr>
<td width="119" style="width: 92px"><div align="right" style="width: 104px">批处理文件:</div></td>
<td width="507" colspan="2" style="width: 806px; height: 48px"><input type="text" name="batfile" value="<%=batfile %>" style="width: 659px">
<input type="submit" name="Submit" value="执行批处理。。。" style="width: 130px"> </td>
</tr>
<tr>
<td colspan="3"><%=msg %><br/><%=line %></td>
</tr>
</table>
</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: