1. 程式人生 > >利用Apache Commons Exec呼叫命令列並取得命令列的輸出(例項)

利用Apache Commons Exec呼叫命令列並取得命令列的輸出(例項)

public String ping(String ip) {

        try {

            String command = "ping "+ip;

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            ByteArrayOutputStream errorStream = new ByteArrayOutputStream();

            CommandLine commandline = CommandLine.parse(command);

            DefaultExecutor exec = new DefaultExecutor();

            exec.setExitValues(null);

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream,errorStream);

            exec.setStreamHandler(streamHandler);

            exec.execute(commandline);

            String out = outputStream.toString("gbk");

            String error = errorStream.toString("gbk");

            return out+error;

        } catch (Exception e) {

            log.error("ping task failed.",e);

            return e.toString();

        }

    }
官方教程參考:http://commons.apache.org/exec/tutorial.html