1. 程式人生 > >Java 執行系統命令工具類

Java 執行系統命令工具類

row com enc log tostring mha comm span onf

依賴jar

        <!-- 可以在JVM中可靠地執行外部進程的庫。 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>1.3</version>
        </dependency>

CommandUtils.java

package
utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.ExecuteWatchdog; import
org.apache.commons.exec.PumpStreamHandler; /** * 執行系統命令工具類 * * @author Logen * */ public class CommandUtils { private static final String DEFAULT_CHARSET = "GBK"; /** * 執行指定命令 * * @param command 命令 * @return 命令執行完成返回結果 * @throws IOException 失敗時拋出異常,由調用者捕獲處理
*/ public static String exeCommand(String command) throws IOException { try ( ByteArrayOutputStream out = new ByteArrayOutputStream(); ) { int exitCode = exeCommand(command, out); if (exitCode == 0) { System.out.println("命令運行成功!"); } else { System.out.println("命令運行失敗!"); } return out.toString(DEFAULT_CHARSET); } } /** * 執行指定命令,輸出結果到指定輸出流中 * * @param command 命令 * @param out 執行結果輸出流 * @return 執行結果狀態碼:執行成功返回0 * @throws ExecuteException 失敗時拋出異常,由調用者捕獲處理 * @throws IOException 失敗時拋出異常,由調用者捕獲處理 */ public static int exeCommand(String command, OutputStream out) throws ExecuteException, IOException { CommandLine commandLine = CommandLine.parse(command); PumpStreamHandler pumpStreamHandler = null; if (null == out) { pumpStreamHandler = new PumpStreamHandler(); } else { pumpStreamHandler = new PumpStreamHandler(out); } // 設置超時時間為10秒 ExecuteWatchdog watchdog = new ExecuteWatchdog(10000); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(pumpStreamHandler); executor.setWatchdog(watchdog); return executor.execute(commandLine); } public static void main(String[] args) { try { String result = exeCommand("ipconfig /all"); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } } }

.

Java 執行系統命令工具類