代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class TracertUtil {
String tracert = "tracert -d"; // 模拟tracert命令
List<String> list = new ArrayList();
/**
* tracert命令运行并输出结果
* @param ip
*/
public void Tracert(String ip, String maxnum, String overtime) {
// 最大跃点数
if (!"".equals(maxnum)) {
tracert = tracert + " -h " + maxnum;
}
// 超时时间
if (!"".equals(overtime)) {
tracert = tracert + " -w " + maxnum;
}
tracert = tracert + " " + ip;
System.out.println("执行的命令:" + tracert);
try {
command(tracert); // 执行tracert命令
list.remove(0); // 删除结果中的第一行空行
// 输出结果
for (String s:list) {
System.out.println(s);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
/**
* 执行 tracert 命令
* @param tracerCommand
* @return
* @throws IOException
*/
private void command(String tracerCommand) throws IOException{
// 通过Runtime类的getRuntime().exec()传入需要运行的命令参数
Process process = Runtime.getRuntime().exec(tracerCommand);
// 读取命令执行结果
readResult(process.getInputStream());
process.destroy();
}
/**
* 通过输入流来将命令执行结果赋值给list
* @param inputStream
* @return
* @throws IOException
*/
private void readResult(InputStream inputStream) throws IOException{
String commandInfo = null; // 定义用于接收命令行执行结果的字符串
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ( (commandInfo = bufferedReader.readLine()) != null) {
list.add(commandInfo); // 将运行结果添加到 list 中
}
bufferedReader.close();
}
public static void main(String[] args) {
TracertUtil util = new TracertUtil();
util.Tracert("baidu.com", "10", "10");
}
}
运行截图: