执行non-Java processes命令行的工具ExecHelper
在Java程序里执行操作命令行工具类:
public static void main(String[] args) { try {
/*String file = ExecHelper.exec(
new String[]{"XXXX"}, "GBK"
).getOutput(); String hello = ExecHelper.execUsingShell(
"echo 'Hello World'"
).getOutput();*/ ExecHelper helper = ExecHelper.execUsingShell("java -version", "GBK");
System.out.println(helper.getResult());
} catch (IOException e) {
e.printStackTrace();
}
}
输出结果:
java version "1.6.0_37"
Java(TM) SE Runtime Environment (build 1.6.0_37-b06)
Java HotSpot(TM) Client VM (build 20.12-b01, mixed mode, sharing)
ExecHelper代码实现:
package com.yzu.zhang.utils; import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader; /**
* Convenience methods for executing non-Java processes.
* @since ostermillerutils 1.06.00
*/
public final class ExecHelper { /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray), null);
} /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray, String[] envp) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray, envp), null);
} /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray, String[] envp, File dir) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray, envp), null);
} /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray, String charset) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray), charset);
} /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray, String[] envp, String charset) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray, envp), charset);
} /**
* Executes the specified command and arguments in a separate process, and waits for the
* process to finish.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper exec(String[] cmdarray, String[] envp, File dir, String charset) throws IOException {
return new ExecHelper(Runtime.getRuntime().exec(cmdarray, envp), charset);
} /**
* Executes the specified command using a shell. On windows uses cmd.exe or command.exe.
* On other platforms it uses /bin/sh.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper execUsingShell(String command) throws IOException {
return execUsingShell(command, null);
} /**
* Executes the specified command using a shell. On windows uses cmd.exe or command.exe.
* On other platforms it uses /bin/sh.
* @since ostermillerutils 1.06.00
*/
public static ExecHelper execUsingShell(String command, String charset) throws IOException {
if (command == null) throw new NullPointerException();
String[] cmdarray;
String os = System.getProperty("os.name");
if (os.equals("Windows 95") || os.equals("Windows 98") || os.equals("Windows ME")){
cmdarray = new String[]{"command.exe", "/C", command};
} else if (os.startsWith("Windows")){
cmdarray = new String[]{"cmd.exe", "/C", command};
} else {
cmdarray = new String[]{"/bin/sh", "-c", command};
}
return new ExecHelper(Runtime.getRuntime().exec(cmdarray), charset);
} /**
* Take a process, record its standard error and standard out streams, wait for it to finish
*
* @param process process to watch
* @throws SecurityException if a security manager exists and its checkExec method doesn't allow creation of a subprocess.
* @throws IOException - if an I/O error occurs
* @throws NullPointerException - if cmdarray is null
* @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0).
*
* @since ostermillerutils 1.06.00
*/
private ExecHelper(Process process, String charset) throws IOException {
StringBuffer output = new StringBuffer();
StringBuffer error = new StringBuffer(); Reader stdout;
Reader stderr; if (charset == null){
// This is one time that the system charset is appropriate,
// don't specify a character set.
stdout = new InputStreamReader(process.getInputStream());
stderr = new InputStreamReader(process.getErrorStream());
} else {
stdout = new InputStreamReader(process.getInputStream(), charset);
stderr = new InputStreamReader(process.getErrorStream(), charset);
}
char[] buffer = new char[1024]; boolean done = false;
boolean stdoutclosed = false;
boolean stderrclosed = false;
while (!done){
boolean readSomething = false;
// read from the process's standard output
if (!stdoutclosed && stdout.ready()){
readSomething = true;
int read = stdout.read(buffer, 0, buffer.length);
if (read < 0){
readSomething = true;
stdoutclosed = true;
} else if (read > 0){
readSomething = true;
output.append(buffer, 0, read);
}
}
// read from the process's standard error
if (!stderrclosed && stderr.ready()){
int read = stderr.read(buffer, 0, buffer.length);
if (read < 0){
readSomething = true;
stderrclosed = true;
} else if (read > 0){
readSomething = true;
error.append(buffer, 0, read);
}
}
// Check the exit status only we haven't read anything,
// if something has been read, the process is obviously not dead yet.
if (!readSomething){
try {
this.status = process.exitValue();
done = true;
} catch (IllegalThreadStateException itx){
// Exit status not ready yet.
// Give the process a little breathing room.
try {
Thread.sleep(100);
} catch (InterruptedException ix){
process.destroy();
throw new IOException("Interrupted - processes killed");
}
}
}
} this.output = output.toString();
this.error = error.toString();
} /**
* The output of the job that ran.
*
* @since ostermillerutils 1.06.00
*/
private String output; /**
* Get the output of the job that ran.
*
* @return Everything the executed process wrote to its standard output as a String.
*
* @since ostermillerutils 1.06.00
*/
public String getOutput(){
return output;
} /**
* The error output of the job that ran.
*
* @since ostermillerutils 1.06.00
*/
private String error; /**
* Get the error output of the job that ran.
*
* @return Everything the executed process wrote to its standard error as a String.
*
* @since ostermillerutils 1.06.00
*/
public String getError(){
return error;
} /**
* The status of the job that ran.
*
* @since ostermillerutils 1.06.00
*/
private int status; /**
* Get the status of the job that ran.
*
* @return exit status of the executed process, by convention, the value 0 indicates normal termination.
*
* @since ostermillerutils 1.06.00
*/
public int getStatus(){
return status;
} public String getResult(){
if(!StringUtils.isBlank(output, error)){
return output + "\n\n" +error;
}
if(StringUtils.isNotBlank(output)){
return output;
}
if(StringUtils.isNotBlank(error)){
return error;
}
return null;
}
}
执行non-Java processes命令行的工具ExecHelper的更多相关文章
- Jsonschema2pojo从JSON生成Java类(命令行)
1.说明 jsonschema2pojo工具可以从JSON Schema(或示例JSON文件)生成Java类型, 在文章Jsonschema2pojo从JSON生成Java类(Maven) 已经介绍过 ...
- 分区表,桶表,外部表,以及hive一些命令行小工具
hive中的表与hdfs中的文件通过metastore关联起来的.Hive的数据模型:内部表,分区表,外部表,桶表受控表(managed table):包括内部表,分区表,桶表 内部表: 我们删除表的 ...
- libvirt 命令行交互工具之virsh
libvirt是当前主流VM最低层库.IBM PowerVM也不例外,libvirt是深入玩虚拟化必须玩转的东西; 简单测试玩玩libvirt 的virsh命令行交互工具, 你我都知libvirt大体 ...
- You-Get 视频下载工具 Python命令行下载工具
You-Get 是一个命令行工具, 用来下载各大视频网站的视频, 是我目前知道的命令行下载工具中最好的一个, 之前使用过 youtube-dl, 但是 youtube-dl 吧, 下载好的视频是分段的 ...
- Cmder | 一款命令行增强工具
文章目录 什么是cmder 安装cmder 让cmder便于使用 将cmder添加到右键菜单中 在设置中添加语言环境 设置默认使用cmd.PowerShell还是bash 调节背景的透明度 添加 ll ...
- virsh命令行管理工具
virsh命令行管理工具 Libvirt有两种控制方式,命令行和图形界面 图形界面: 通过执行名virt-manager,启动libvirt的图形界面,在图形界面下可以一步一步的创建虚拟机,管理虚拟机 ...
- 通过JAVA调用命令行程序
这是我在把数据导入到数据库时遇到问题,总结下来的.包含两个方法,一个方法是读取文件路径下的文件列表,主方法是执行cmd命令,在导入时想得到导入一个文件的时间,涉及到线程阻塞问题,这个问题理解不是很深, ...
- 推荐一个高大上的网易云音乐命令行播放工具:musicbox
网易云音乐上有很多适合程序猿的歌单,但是今天文章介绍的不是这些适合程序员工作时听的歌,而是一个用Python开发的开源播放器,专门适用于网易云音乐的播放.这个播放器的名称为MusicBox, 特色是用 ...
- ElasticSearch 命令行管理工具Curator
一.背景 elastic官网现在已经大面积升级到了5.x版本,然而针对elasticsearch的命令行管理工具curator现在仍然是4.0版本. 刚开始找到此工具,深深的怕因为版本更迭无法使用,还 ...
随机推荐
- sys.dm_os_waiting_tasks 引发的疑问(中)
上一篇我们说了一下sys.dm_exec_requests 和 sys.dm_os_waiting_tasks 在获取并行等待的时候得不同结果,这一篇我们谈论下我的第二个疑问:为什么一个并行计划(4线 ...
- Linux运维之基础拾遗
第一部分 Linux常用文件管理命令 1.1 cp 文件复制 常用选项 -i # 覆盖之前提醒用户确认 -f # 强制覆盖目标文件 -r # 递归复制目录 -d # 复制符号链接本身而非其指向的源文件 ...
- 树莓派3B远程VNC的设置(包括开机启动)
可以说,现在很少有自带VNCserver的教程 因为之前 官方系统没有自带VNC 但是 现在 最新版的官方系统已经自带VNCserver 只需要在设置里启用一下,然后设置就可以用啦. 别的教程都是 ...
- java环境变量配置
1.打开我的电脑--属性--高级--环境变量 2.新建系统变量JAVA_HOME 和CLASSPATH 变量名:JAVA_HOME 变量值:C:\Program Files\Java\jdk1.7.0 ...
- js 页面无滚动条添加滚轮事件
当页面无滚动条时,滑动滚轮时window.onscroll事件不会相应,此时应该去添加滚轮事件 var MouseWheelHandler=function(e){ e.preventDefault( ...
- js入门学习~ 运动应用小例
要实现的效果如下: 鼠标移入各个小方块,实现对应的效果(变宽,变高,移入透明,移出恢复)~~ (且各运动相互之前不干扰) 主要是练习多个物体的运动框架~~ --------------------- ...
- 一个简单的ASP.NET MVC异常处理模块
一.前言 异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示.记录错误信息,更重要的是不破坏正常的数据和影响系统运行.异常处理应该是一个横切点,所谓横切点就是各个部分都 ...
- VS调试经常打断点打上之后没反应的问题
在调试的时候经常会发现打了断点但是始终不进到程序中来,这是因为访问的这个页面在服务器中有缓存,也就是在iis中产生了缓存.访问的时候直接进到读取的缓存文件, 根本没有读取项目文件,所以打了断点肯定进不 ...
- Python学习--Python 环境搭建
Python环境搭建 Python是跨平台的编程语言,可应用于Windows.Linux.Mac OS X.你可以通过终端窗口输入"python"命令来查看本地是否安装了Pytho ...
- 多线程异步导出excel
先新建一个执行类 @Service public class MultiService { private static final Logger logger = LoggerFactory.get ...