Java 執行Windows 命令列
阿新 • • 發佈:2019-01-22
有時候,專案需要用Java 語言執行系統命令,Javva 執行命令的方式也非常簡單。
【1. 工具類】
package org.zgf.robot.util; /** * @ClassName: EsecUtil * @Description: 執行命令列工具類 * @author: zonggf * @date: 2015年12月1日 下午3:05:37 */ public class ExcuteCommandUtil { /** * @Title: excuteCommand * @Description: 執行command 命令 * @param command * @return * @return: boolean * @author: zonggf * @time: 2015年12月1日 下午3:08:04 */ public static boolean excute(String command){ try{ Runtime.getRuntime().exec(command); return true; }catch(Exception ex){ System.out.println("執行命令:" + command + "錯誤"); } return false; } }
【2.常量類 】
package org.zgf.robot.constant; /** * @ClassName: EscConstant * @Description: 可執行的esc列表 * @author: zonggf * @date: 2015年12月1日 下午12:25:56 */ public class CommandConstant { /** 開啟記事本 */ public static String openNotepad = "notepad"; /** 開啟命令列 */ public static String openCmd = "cmd"; /** 開啟控制面板 */ public static String openControl = "control"; /** 關機命令 */ public static String shutDown = "shutdown -s"; }
【3. 測試類】
package org.zgf.robot.util; import org.junit.Test; import org.zgf.robot.constant.CommandConstant; /** * @ClassName: Test_ExcuteCommandUtil * @Description: 測試執行命令 * @author: zonggf * @date: 2015年12月1日 下午3:10:39 */ public class Test_ExcuteCommandUtil { /** 開啟命令列 */ @Test public void test_openCmd(){ ExcuteCommandUtil.excute(CommandConstant.openCmd); } /** 開啟控制面板 */ @Test public void test_openControl(){ ExcuteCommandUtil.excute(CommandConstant.openControl); } /** 開啟記事本 */ @Test public void test_openNotepad(){ ExcuteCommandUtil.excute(CommandConstant.openNotepad); } /** 關機 */ @Test public void test_shutDown(){ ExcuteCommandUtil.excute(CommandConstant.shutDown); } }
【4.原始碼下載】Java 操控鍵盤,滑鼠,剪下板Demo