代码如下:
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");}
}
运行截图:
本文链接:https://my.lmcjl.com/post/12730.html
展开阅读全文
4 评论