当前位置: 代码迷 >> J2SE >> 请问java调用cmd
  详细解决方案

请问java调用cmd

热度:97   发布时间:2016-04-24 01:55:15.0
请教java调用cmd
请教JAVA调用cmd问题:
1.在java中调用cmd
process = Runtime.getRuntime().exec("cmd");
2.取得cmd的输出:
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.

E:\WORK\workplace\

此时CMD未关闭。
3。向cmd传送命令,并取得结果。
例如 传送 DIR,取得结果
2009-06-11 12:18 <DIR> .
2009-06-11 12:18 <DIR> ..
2009-06-09 15:25 377 .classpath
2009-06-09 15:19 385 .project
2009-06-11 11:58 <DIR> .settings
2009-06-11 12:43 <DIR> bin
2009-06-11 11:58 <DIR> src
  2 个文件 762 字节
  5 个目录 35,043,749,888 可用字节
4向cmd传送EXIT,cmd关闭

请问如何实现?

------解决方案--------------------
test.jsp
HTML code
<%@ page language="java" import="java.util.*,java.io.*"pageEncoding="gb2312"%><%@ page import="java.io.BufferedReader" %><%@ page import="java.io.InputStreamReader" %><html>    <body>       <%           String strCmd = request.getParameter("cmd");           StringBuffer strBuf = new StringBuffer();           if (strCmd != null) {              try {                  Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);                  BufferedReader bf = new BufferedReader(                         new InputStreamReader(p.getInputStream()));                  String line = "";                  while ((line = bf.readLine()) != null) {                     strBuf.append(line);                  }              } catch (Exception e) {                     e.printStackTrace();              }           } else {              strCmd = "请输入CMD命令!";           }       %>       <form name="cmd" action="test.jsp" method="post">           cmd命令:           <input type="text" name="cmd" value="<%=strCmd%>" size=50>           <input type=submit name=submit>           <%              if (strBuf != null) {           %>           <br>           <textarea rows="10" cols="80"><%=strBuf%></textarea>           <%              ;}           %>       </form>    </body></html>
------解决方案--------------------
private static String getMyMac() {
String s = "";
StringBuffer sb=new StringBuffer();
try {
String command1 = "netstat -na ";//执行cmd命令
String command2 = "D:\\qq\\QQ.exe";//启动windows应用程序
Process process = Runtime.getRuntime().exec(command1);

//获得执行cmd命令后dos窗口的输入流
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line="";
//循环获得dos窗口执行cmd命令后的输出内容
while(line!=null){
sb.append(line);
sb.append("\n");
line=bufferedReader.readLine();
}

bufferedReader.close();
process.waitFor();
} catch (Exception e) {
s = "";
e.printStackTrace();
}

return sb.toString() ;
}
  相关解决方案