commons-exec执行系统命令
来源:互联网 发布:朋友圈视频转发软件 编辑:程序博客网 时间:2024/05/29 18:39
有些场景下需要在java中执行Bat命令或者Shell命令,如使用wkhtmltopdf生成pdf报表等,这时可以借助apache的commons-exec,指定ExecuteWatchdog 可以完整控制整个执行声明周期,不会产生失控进程。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version> </dependency>
/** * 执行不需要返回结果的命令 * @throws Exception */ public void execCmdWithoutResult() throws Exception{ //开启windows telnet: net start telnet //注意:第一个空格之后的所有参数都为参数 CommandLine cmdLine = new CommandLine("net"); cmdLine.addArgument("start"); cmdLine.addArgument("telnet"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(1); //设置60秒超时,执行超过60秒后会直接终止 ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); executor.setWatchdog(watchdog); DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler(); executor.execute(cmdLine, handler); //命令执行返回前一直阻塞 handler.waitFor(); } /** * 带返回结果的命令执行 * @return */ private String execCmdWithResult() { try { String command = "ping 192.168.1.10"; //接收正常结果流 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //接收异常结果流 ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); //设置一分钟超时 ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000); exec.setWatchdog(watchdog); 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) { e.printStackTrace(); return e.getMessage(); } }
阅读全文
1 0
- commons-exec执行系统命令
- 禁止JVM执行外部命令Runtime.exec -- 由Apache Commons Collections漏洞引发的思考
- Java执行外部程序(Apache Commons Exec)
- Java执行外部程序(Apache Commons Exec)
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- exec() 执行系统的某些命令的函数
- PHP 执行系统外部命令 system() exec() passthru()
- PHP 执行系统外部命令 system() exec() passthru()
- PHP执行系统命令 exec,system,passthru,popen
- PHP 执行系统外部命令 system() exec() passthru()
- php使用exec系统命令执行mysqldump备份数据库
- 算法:快速排序
- LogLog Counting
- 关于如何保持图片分辨率并压缩图片存储大小
- 求以邻接矩阵存储的有向无环图中的最长路径
- Unity 导航网格生成碰撞体
- commons-exec执行系统命令
- 笔记-2017.10.24
- 输入多组数据,输入0结束
- HyperLogLog Counting
- LeetCode 8. String to Integer (atoi)
- Hbase 数据写入
- ArcEngine对shp文件的操作(代码总结)
- 自媒体人必备:国内最专业的自媒体平台导航网站,有它就够了
- java中split时,需要转义的几个字符