import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* 终端命令工具
*
* @author JHL
* @version 1.0
* @date 2023/11/7 14:15
* @since : JDK 11
*/
public class CommandUtil {
/**
* 终端程序
* windows下为 cmd
* linux/mac下为 [ sh | bash | ... ]
*/
public static final String COMMAND_SH = "cmd";
/**
* 终端-行结束符
*/
public static final String COMMAND_LINE_END = "\n";
/**
* 终端-退出命令
*/
public static final String COMMAND_EXIT = "exit\n";
/**
* 调试模式
*/
private static final boolean IS_DEBUG = true;
/**
* 执行单条命令
*/
public static List<String> execute(String command) {
return execute(new String[]{command});
}
/**
* 可执行多行命令(bat)
*/
public static List<String> execute(String[] commands) {
List<String> results = new ArrayList<>();
int status = -1;
if (commands == null || commands.length == 0) {
return null;
}
debug("所有要执行的命令: " + String.join(" ", commands));
Process process = null;
BufferedReader successReader = null;
BufferedReader errorReader = null;
StringBuilder errorMsg = null;
DataOutputStream dos = null;
try {
process = Runtime.getRuntime().exec(COMMAND_SH);
dos = new DataOutputStream(process.getOutputStream());
// 依次执行每条命令
for (String command : commands) {
if (command == null) {
continue;
}
dos.write(command.getBytes());
dos.writeBytes(COMMAND_LINE_END);
dos.flush();
debug("执行命令: " + command);
}
// 退出
dos.writeBytes(COMMAND_EXIT);
dos.flush();
// 等待执行代码 0 正常执行完毕退出
status = process.waitFor();
// 读取进程标准正常输出
successReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String lineStr;
while ((lineStr = successReader.readLine()) != null) {
results.add(lineStr + "\n");
}
debug("命令行输出: \n" + String.join("", results));
// 读取进程错误输出
errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorMsg = new StringBuilder();
while ((lineStr = errorReader.readLine()) != null) {
errorMsg.append(lineStr + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
if (successReader != null) {
successReader.close();
}
if (errorReader != null) {
errorReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (process != null) {
process.destroy();
}
}
debug(String.format(Locale.CHINA, "命令执行结束,错误消息:%s,执行状态码:%d", errorMsg, status));
return results;
}
/**
* DEBUG LOG
*
* @param message
*/
private static void debug(String message) {
if (IS_DEBUG) {
System.out.println("######################### \t " + message);
}
}
public static void main(String[] args) {
List<String> result = CommandUtil.execute("ping 192.168.100.40");
}
}
标签:java,String,static,终端,new,dos,工具,null
From: https://www.cnblogs.com/hhddd-1024/p/17815297.html