java终端命令工具
示例一
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @author JHL
* @version 1.0
* @since : 2023/11/19 23:20
*/
public class SystemCommand extends Thread {
private Process process;
private OutputStream write;
private InputStream read;
private List<String> result = new ArrayList<>();
private InputStream err;
private List<String> errResult = new ArrayList<>();
private static final String finishFlag = "\n";
private Long readWaitTimeOut;
private volatile Boolean doStop = false;
public SystemCommand(TerminalType terminal, Long readWaitTimeOut) throws IOException {
this.process = Runtime.getRuntime().exec(terminal.name);
this.read = process.getInputStream();
this.write = process.getOutputStream();
this.err = process.getErrorStream();
this.readWaitTimeOut = readWaitTimeOut;
this.start();
}
public void execCommand(String command) throws IOException, InterruptedException {
result.clear();
errResult.clear();
write.write((command + finishFlag).getBytes(StandardCharsets.UTF_8));
write.flush();
Thread.sleep(readWaitTimeOut);
}
@Override
public void run() {
while (!doStop) {
try {
int available = read.available();
if (available > 0) {
byte[] data = new byte[available];
read.read(data);
result.add(new String(data, StandardCharsets.UTF_8));
}
int eAvailable = err.available();
if (eAvailable > 0) {
byte[] data = new byte[eAvailable];
err.read(data);
errResult.add(new String(data, StandardCharsets.UTF_8));
}
} catch (Exception e) {
e.printStackTrace();
}
}
try {
read.close();
write.close();
err.close();
} catch (IOException e) {
e.printStackTrace();
read = null;
write = null;
err = null;
}
process.destroy();
}
public static enum TerminalType {
CMD("cmd"), SH("sh");
private String name;
TerminalType(String name) {
this.name = name;
}
}
public static void main(String[] args) throws IOException, InterruptedException {
SystemCommand c = new SystemCommand(TerminalType.CMD, 1000L);
c.execCommand("ping 127.0.0.1");
System.out.println("######################### \t[ " + c.result + " ]\t #########################");
System.out.println("######################### \t[ " + c.errResult + " ]\t #########################");
c.doStop = true;
while (true) {
}
}
}
示例二
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 String COMMAND_SH = "";
static {
String property = System.getProperty("os.name");
if (StrUtil.containsIgnoreCase(property, "Windows")) {
COMMAND_SH = "cmd";
} else if (StrUtil.containsIgnoreCase(property, "linux")) {
COMMAND_SH = "bash";
}
}
/**
* 终端-行结束符
*/
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");
}
}