更新時間:2022-05-24 10:45:04 來源:動力節(jié)點 瀏覽3036次
Java執(zhí)行本地命令,可以用Runtime實現(xiàn),也可以用ProcessBuilder實現(xiàn)。無論使用哪種方式,必須要給正確的執(zhí)行命令,例如打開文件夾的命令是explorer.exe,打開txt文件notepad.exe等,注意:
對于不同的文件后綴,應該使用正確的命令。
執(zhí)行帶有參數(shù)的命令,命令和參數(shù)一定要在一個數(shù)組或集合內(nèi)
Runtime案例:
String path = System.getProperty("user.dir");
String filePath = path + "/key.txt";
File file = new File(filePath);
file.createNewFile();
// 使用 windows 自帶的文本編輯器打開 txt 文件,命令和參數(shù)在一個數(shù)組內(nèi)
String cmdTxt[] = { "notepad.exe", filePath };
Runtime.getRuntime().exec(cmdTxt);
// 打開文件夾,命令和參數(shù)在一個數(shù)組內(nèi)
String cmdDir[] = { "explorer.exe", path };
Runtime.getRuntime().exec(cmdDir);
ProcessBuilder案例:
ProcessBuilder pb = new ProcessBuilder();
List<String> commands = new ArrayList<>();
// 命令和參數(shù)在一個集合內(nèi)
commands.add("notepad.exe");
commands.add(filePath);
pb.command(commands);
pb.start();