-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProcessUtil.java
86 lines (73 loc) · 1.97 KB
/
ProcessUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package javaToolkit.lib.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
public class ProcessUtil {
public static class ProcessReporter {
public String cmd;
public int exitCode;
public String out;
public String err;
public ProcessReporter() {
this.cmd = null;
this.exitCode = -1;
this.out = null;
this.err = null;
}
@Override
public String toString() {
String res = "Process Report:\n";
res += ("cmd:\n" + this.cmd + "\n");
res += ("exit code:\n" + this.exitCode + "\n");
res += ("out:\n" + this.out + "\n");
res += ("err:\n" + this.err + "\n");
return res;
}
}
/**
* execute cmd
*
* @param cmd
* @param envp
* @param workDir
* @return
*/
public static ProcessReporter executeCMD(String cmd, String[] envp, Path workDir) {
ProcessReporter pr = new ProcessReporter();
pr.cmd = cmd;
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd, envp, workDir.toFile());
pr.exitCode = proc.waitFor();
// Read the output from the command
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// System.out.println("Here is the standard output of the
// command:\n");
String out = "";
String s = null;
while ((s = stdInput.readLine()) != null) {
// System.out.println(s);
out += (s + "\n");
}
pr.out = out.trim();
// Read any errors from the attempted command
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// System.out.println("Here is the standard error of the command (if
// any):\n");
String err = "";
while ((s = stdError.readLine()) != null) {
// System.out.println(s);
err += (s + "\n");
}
pr.err = err.trim();
proc.destroy();
if (pr.exitCode != 0) {
throw new Exception();
}
} catch (Exception e) {
TimeUtil.printCurTimewithMsg(pr.toString());
e.printStackTrace();
}
return pr;
}
}