1.实现方式
在Java中提供了两种实现方式:Runtime和ProcessBuilder
1) Runtime是Java中的运行时类:
Runtime.getRuntime().exec(String cmd);可以直接通过exec方法调用
***eg(Runtime方式)***:
//直接通过cmd打开notepad记事本
Process exec=Runtime.getRuntime().exec("cmd /k start notepad");
//打印Java环境变量
Proecess exec2=Runtime.getRuntime().exec("cmd /c echo %Java_Home%");
//获得流对象,可以将其输出到控制台
InputStream in = exec2.getInputStream();
//...
2) ProcessBuilder是进程管理相关的类
***eg(ProcessBuilder方式)***:
ProcessBuilder pb=new ProcessBuilder("cmd","/c",cmd命令);
Process process = pb.start();
//获得流对象,可以将其输出到控制台
InputStreamReader reader = new InputStreamReader(process.getInputStream());
2.通过ProcessBuilder将命令输出结果展示到web页面
基于Tomcat的idea web项目
MyServlet.java:
package com.mycat.core; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @WebServlet("/myser") public class MyServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=utf-8"); resp.setCharacterEncoding("utf-8"); String cmd = req.getParameter("cmd").trim(); ProcessBuilder pb=new ProcessBuilder("cmd","/c",cmd); Process process = pb.start(); InputStreamReader reader = new InputStreamReader(process.getInputStream()); BufferedReader bf=new BufferedReader(reader); StringBuilder message=new StringBuilder(); String smg=""; while((smg=bf.readLine())!=null){ message.append(smg).append("\n"); } reader.close(); req.setAttribute("result", message.toString()); req.setAttribute("cmd", cmd); req.getRequestDispatcher("index.jsp").forward(req, resp); } }
index.jsp页面:
<%-- Created by IntelliJ IDEA. User: mycat Date: 2019/2/23 Time: 14:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.servletContext.contextPath}/myser" method="post"> 请输入命令:<input type="text" name="cmd" value="${cmd}"><br/> 执行结果:<div name="result" style="border: 2px solid red;padding: 20px;">${result}</div> <input type="submit" value="查询"/> </form> </body> </html>
效果图:
只需在上面的文本框输入cmd的命令,点击查询按钮后,就可以在div盒子中显示输出内容,上图便是输出的Path环境变量的内容,也可以在文本框输入 echo 234 等。