首页 课程 师资 教程 报名

Java执行cmd命令的方式

  • 2022-12-12 12:37:23
  • 2558次 动力节点

Java执行cmd命令的方式有哪些?动力节点小编来告诉大家。

方式一:

public static String checkPhysicalAddress() {
  String physicalAddress = "read MAC error!";  
  try {
   String line;
   Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all");
   BufferedReader bufferedReader = new BufferedReader(
     new InputStreamReader(process.getInputStream(),"gbk"));//使用gbk编码解决输出乱码问题
   while ((line = bufferedReader.readLine()) != null) {
    if (line.indexOf("Physical Address. . . . . . . . . :") != -1) {
     if (line.indexOf(":") != -1) {
      physicalAddress = line.substring(line.indexOf(":") + 2);
      break; // 找到MAC,退出循环
     }
    }
   }
   process.waitFor();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return physicalAddress;
 }

方式二:

public static void startProgram(String programPath) throws IOException { 
 log.info("启动应用程序:" + programPath); 
 if (StringUtils.isNotBlank(programPath)) { 
  try { 
   String programName = programPath.substring(programPath.lastIndexOf("/") + 1, programPath.lastIndexOf(".")); 
   List<String> list = new ArrayList<String>(); 
   list.add("cmd.exe"); 
   list.add("/c"); 
   list.add("start"); 
   list.add(""" + programName + """); 
   list.add(""" + programPath + """); 
   ProcessBuilder pBuilder = new ProcessBuilder(list); 
   pBuilder.start(); 
  } catch (Exception e) { 
   e.printStackTrace(); 
   log.error("应用程序:" + programPath + "不存在!"); 
  } 
 } 
} 

方式三:

public static void startProgram(String programPath) throws IOException { 
 log.info("启动应用程序:" + programPath); 
 if (StringUtils.isNotBlank(programPath)) { 
  try { 
   Desktop.getDesktop().open(new File(programPath)); 
  } catch (Exception e) { 
   e.printStackTrace(); 
   log.error("应用程序:" + programPath + "不存在!"); 
  } 
 } 
}

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交