Skip to content

Instantly share code, notes, and snippets.

@AlbertHG
Last active July 26, 2016 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlbertHG/e0e752061b98f321b8c4e9faff4d242c to your computer and use it in GitHub Desktop.
Save AlbertHG/e0e752061b98f321b8c4e9faff4d242c to your computer and use it in GitHub Desktop.
进程控制错误输出简化工具
import java.io.BufferedReader;
import java.io.InputStreamReader;
class OSExecuteException extends RuntimeException {
public OSExecuteException(String why) {
super(why);
}
}
class OSExecute {
public static void command(String command) {
boolean err = false;
try {
//利用指定的操作系统程序和参数构造一个进程生成器,并启动进程
Process process = new ProcessBuilder(command.split(" ")).start();
//getInputStream()获取子进程的输入流。输入流获得由该 Process 对象表示的进程的标准输出流
BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
while ((s = results.readLine()) != null) {
System.out.println(s);
}
//getErrorStream()获取子进程的错误流。错误流获得由该 Process 对象表示的进程的错误输出流传送的数据
BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((s = errors.readLine()) != null) {
System.out.println(s);
err = true;
}
} catch (Exception e) {
//测试此字符串是否以"CMD /C"前缀开始
if (!command.startsWith("CMD /C")) {
command("CMD /C" + command);
} else {
throw new RuntimeException(e);
}
if (err) {
throw new OSExecuteException("Errors executing :" + command);
}
}
}
}
//测试类
public class OSExecuteDemo {
public static void main(String[] args) {
OSExecute.command("javap OSExecuteDemo");
}
}
@AlbertHG
Copy link
Author

一项常见任务是运行程序,并将产生的输出发送到控制台,这个工具可以简化这项任务,在使用这个工具的时候可能会产生两种错误,一种是普通的导致异常的错误——对这种错误我们只需要重新抛出一个运行异常即可;以及从进程自身执行过程中产生的错误。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment