更新時間:2022-12-12 12:37:23 來源:動力節點 瀏覽2574次
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 + "不存在!");
}
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習