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

这个Java代码示例展示了如何调用.bat或.cmd文件,执行CMD命令,并将命令的输出结果显示在页面上。通过Runtime.getRuntime().exec()方法执行批处理文件,并使用InputStream和BufferedReader读取并显示执行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 <%@ 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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值