执行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版本. 刚开始找到此工具,深深的怕因为版本更迭无法使用,还 ...
随机推荐
- 【转】XenServer的架构之Xenopsd组件架构与运行机制
一.Xenopsd概述 Xenopsd是XenServer的虚拟机管理器. Xenopsd负责:启动,停止,暂停,恢复,迁移虚拟机:热插拔虚拟磁盘(VBD):热插拔虚拟网卡(VIF):热插拔虚拟PCI ...
- angularJS(2)
angularJS(2) 今天先讲一个angularJs的表单绑定实例: <div ng-app="myApp" ng-controller="formCtrl&q ...
- Linux的一些基本概述以及系统使用
GNU:项目名称(意指开发在类UNIX系统上的软件).POSIX:可移植(Portable)操作系统接口,便于程序在不同操作系统上运行. Linux是符合POSIX标准的操作系统: 完全兼容POSIX ...
- [LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...
- 如何用卷积神经网络CNN识别手写数字集?
前几天用CNN识别手写数字集,后来看到kaggle上有一个比赛是识别手写数字集的,已经进行了一年多了,目前有1179个有效提交,最高的是100%,我做了一下,用keras做的,一开始用最简单的MLP, ...
- mtk flash tool,Win7 On VirtualBox
SP_Flash_Tool_exe_Windows_v5.1624.00.000 Win7 在 VirtualBox, 安裝 mtk flash tool, v5.1628 在燒錄時會 fail. v ...
- MySQL字符串函数substring:字符串截取
MySQL 字符串截取函数:left(), right(), substring(), substring_index().还有 mid(), substr().其中,mid(), substr() ...
- Extjs 下拉框显示远程数据
var store = new HT.SyncStore({ baseParams : { itemName : '绩效考核_任务状态' }, url : __ctxPath + '/system/l ...
- 【CodeVS 1288】埃及分数
http://codevs.cn/problem/1288/ loli秘制面向高一的搜索,好难啊QAQ 我本来想按照分母从大到小搜,因为这样分母从小到大枚举到的第一个可行方案就是最优方案. 但貌似会T ...
- [HTML5] FileReader对象
写在前面 前一篇文章介绍了HTML5中的Blob对象(详情戳这里),从中了解到Blob对象只是二进制数据的容器,本身并不能操作二进制,故本篇将对其操作对象FileReader进行介绍. FileRea ...