执行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版本. 刚开始找到此工具,深深的怕因为版本更迭无法使用,还 ...
随机推荐
- Oracle索引梳理系列(十)- 直方图使用技巧及analyze table操作对直方图统计的影响(谨慎使用)
版权声明:本文发布于http://www.cnblogs.com/yumiko/,版权由Yumiko_sunny所有,欢迎转载.转载时,请在文章明显位置注明原文链接.若在未经作者同意的情况下,将本文内 ...
- 杂项之图像处理pillow
杂项之图像处理pillow 本节内容 参考文献 生成验证码源码 一些小例子 1. 参考文献 http://pillow-cn.readthedocs.io/zh_CN/latest/ pillow中文 ...
- 解决ASP.NET上传文件大小限制
第一种方法,主要适用于IIS6.0版本 一.修改配置Web.Config文件中的httpRuntime节点对于asp.net,默认只允许上传4M文件,增加如下配置,一般可以自定义最大文件大小.一.修改 ...
- [LeetCode] Number of 1 Bits 位1的个数
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...
- [LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- [LeetCode] Sort List 链表排序
Sort a linked list in O(n log n) time using constant space complexity. 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序, ...
- Html-浅谈如何正确给table加边框
一般来说,给表格加边框都会出现不同的问题,以下是给表格加边框后展现比较好的方式 <style> table,table tr th, table tr td { border:1px so ...
- C++ 数组array与vector的比较
转:http://blog.csdn.net/yukin_xue/article/details/7391897 1. array 定义的时候必须定义数组的元素个数;而vector 不需要: 且只能包 ...
- 【.NET】Cookie操作类
public static class CookiesHelper { /// <summary> /// Cookies赋值 /// </summary> /// <p ...
- android-配置文件AndroidManifest.xml
AndroidManifest.xml 是每个android程序中必须的文件.它位于整个项目的根目录,描述了package中暴露的组件(activities, services, 等等),他们各自的实 ...