2019-08-06 | Java | UNLOCK

java执行cmd命令工具类(windows)

执行windows的cmd命令工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
* 执行windows的cmd命令工具类
*
*/
public class CmdTools {
/**
*公共部分
*/
public static String Commandexecuter(String cmdCommand){
StringBuilder stringBuilder = new StringBuilder();
Process process = null;
try {
process = Runtime.getRuntime().exec(cmdCommand);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), "GBK"));
String line = null;
while((line=bufferedReader.readLine()) != null)
{
stringBuilder.append(line+"\n");
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 执行一个cmd命令
* @param cmdCommand cmd命令
* @return 命令执行结果字符串,如出现异常返回null
*/
public static String excuteCMDCommand(String cmdCommand)
{
return CmdTools.Commandexecuter(cmdCommand);
}
/**
* 执行bat文件,
* @param file bat文件路径
* @param isCloseWindow 执行完毕后是否关闭cmd窗口
* @return bat文件输出log
*/
public static String excuteBatFile(String file, boolean isCloseWindow)
{
String cmdCommand = null;
if(isCloseWindow)
{
cmdCommand = "cmd.exe /c "+file;
}else
{
cmdCommand = "cmd.exe /k "+file;
}
return CmdTools.Commandexecuter(cmdCommand);
}

/**
* 执行bat文件,新开窗口
* @param file bat文件路径
* @param isCloseWindow 执行完毕后是否关闭cmd窗口
* @return bat文件输出log
*/
public static String excuteBatFileWithNewWindow(String file, boolean isCloseWindow)
{
String cmdCommand = null;
if(isCloseWindow)
{
cmdCommand = "cmd.exe /c start"+file;
}else
{
cmdCommand = "cmd.exe /k start"+file;
}
return Commandexecuter(cmdCommand);
}

public static void main(String[] args) {
String cmd = "ping 127.0.0.1";
String result = CmdTools.excuteCMDCommand(cmd);
System.out.println(result);
}
}

查找某进程pid(java):

1
2
3
4
5
6
7
8
9
String result = test.excuteBatFile("findPid.bat",true);
String[] str=result.split("\n");
String[] str=result.split("\n");
String Pid="";
for (int i = 0;i<str.length;i++){
if (str[i].indexOf("cmd.exe")!=-1){
Pid=str[i].split(",")[1].replace("\"","");
}
}
findPid.bat:
1
tasklist /v /fo csv | findstr /i "myprocess"

评论加载中