专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java执行cmd命令的方式

Java执行cmd命令的方式

更新时间:2022-12-12 12:37:23 来源:星辉 浏览1774次

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 + "不存在!"); 
  } 
 } 
}

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>