在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的更多相关文章

  1. Jsonschema2pojo从JSON生成Java类(命令行)

    1.说明 jsonschema2pojo工具可以从JSON Schema(或示例JSON文件)生成Java类型, 在文章Jsonschema2pojo从JSON生成Java类(Maven) 已经介绍过 ...

  2. 分区表,桶表,外部表,以及hive一些命令行小工具

    hive中的表与hdfs中的文件通过metastore关联起来的.Hive的数据模型:内部表,分区表,外部表,桶表受控表(managed table):包括内部表,分区表,桶表 内部表: 我们删除表的 ...

  3. libvirt 命令行交互工具之virsh

    libvirt是当前主流VM最低层库.IBM PowerVM也不例外,libvirt是深入玩虚拟化必须玩转的东西; 简单测试玩玩libvirt 的virsh命令行交互工具, 你我都知libvirt大体 ...

  4. You-Get 视频下载工具 Python命令行下载工具

    You-Get 是一个命令行工具, 用来下载各大视频网站的视频, 是我目前知道的命令行下载工具中最好的一个, 之前使用过 youtube-dl, 但是 youtube-dl 吧, 下载好的视频是分段的 ...

  5. Cmder | 一款命令行增强工具

    文章目录 什么是cmder 安装cmder 让cmder便于使用 将cmder添加到右键菜单中 在设置中添加语言环境 设置默认使用cmd.PowerShell还是bash 调节背景的透明度 添加 ll ...

  6. virsh命令行管理工具

    virsh命令行管理工具 Libvirt有两种控制方式,命令行和图形界面 图形界面: 通过执行名virt-manager,启动libvirt的图形界面,在图形界面下可以一步一步的创建虚拟机,管理虚拟机 ...

  7. 通过JAVA调用命令行程序

    这是我在把数据导入到数据库时遇到问题,总结下来的.包含两个方法,一个方法是读取文件路径下的文件列表,主方法是执行cmd命令,在导入时想得到导入一个文件的时间,涉及到线程阻塞问题,这个问题理解不是很深, ...

  8. 推荐一个高大上的网易云音乐命令行播放工具:musicbox

    网易云音乐上有很多适合程序猿的歌单,但是今天文章介绍的不是这些适合程序员工作时听的歌,而是一个用Python开发的开源播放器,专门适用于网易云音乐的播放.这个播放器的名称为MusicBox, 特色是用 ...

  9. ElasticSearch 命令行管理工具Curator

    一.背景 elastic官网现在已经大面积升级到了5.x版本,然而针对elasticsearch的命令行管理工具curator现在仍然是4.0版本. 刚开始找到此工具,深深的怕因为版本更迭无法使用,还 ...

随机推荐

  1. android 闪屏还是会出现黑屏问题

    public class SplashActivity extends Activity{ @Override protected void onCreate(Bundle savedInstance ...

  2. After the exam

    离散数学考完啦!!!自我感觉还行,或许得不到高分,但是过的话是没问题了.(但愿成绩出来后不打脸) 持续了两周的复习,告一段落了.那么,今天就休息休息吧. 今天阴有雨,走过的地儿都是湿漉漉.滑溜溜的.这 ...

  3. [poj1741][tree] (树/点分治)

    Description Give a tree with n vertices,each edge has a length(positive integer less than 1001). Def ...

  4. javascript中的原型和继承

    javascript一直是初学者口中的难点,甚至一些有些许工作经验的人也不太明白其中的原理,而我就是那个初学者,前段时间在阮一峰老师的博客上看了一篇文章<javascript继承机制的设计思想& ...

  5. 浏览器控制台命令调试——console

    控制台命令调试时通过浏览器开发工具中的控制台命令嵌入到JavaScript中,输出特定的信息或日志,从而达到调试的目的. 我们常用的Chrome和FireFox,都可以通过F12来打开开发工具. 下面 ...

  6. NIO服务器

    导语 NIO的出现是为服务器端编程而设计的.它的作用就是能够让一个线程为多个连接服务.NIO中的API都是非阻塞模式的,这样可以在服务器端采用异步的方式来处理多个请求.NIO中有两个重要的东西就是通道 ...

  7. [转] eclipse SVN中文件修改后图标不变黑星解决

    原文地址:http://blog.csdn.net/luwei42768/article/details/39225641 版权声明:本文为博主原创文章,未经博主允许不得转载. 如上图, 如果文件修改 ...

  8. vuex 初体验

    vuex是vue的状态管理工具,vue进阶从es6和npm开始,es6推荐阮一峰大神的教程. vuex学习从官方文档和一个记忆小游戏开始.本着兴趣为先的原则,我先去试玩了一把-->. Vuex ...

  9. 将字符串中的URL 解析,获取内容

    parse_str() : parse_str("name=Bill&age=60"); echo $name."<br>";//Bill ...

  10. BZOJ 1876: [SDOI2009]SuperGCD

    1876: [SDOI2009]SuperGCD Time Limit: 4 Sec  Memory Limit: 64 MBSubmit: 3060  Solved: 1036[Submit][St ...