blob: 03f1de9770bfbfa29b6f95981823a58101a35666 (
plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
/* RunCommand.java */
import java.io.*;
public class RunCommand
{
static final int MODE_UNCONNECTED = 0;
static final int MODE_WAITFOR = 1;
static final int MODE_CATCHOUTPUT = 2;
private static void runCommand(String cmd, int mode)
throws IOException
{
Runtime rt = Runtime.getRuntime();
System.out.println("Running " + cmd);
Process pr = rt.exec(cmd);
if (mode == MODE_WAITFOR) {
System.out.println("waiting for termination");
try {
pr.waitFor();
} catch (InterruptedException e) {
}
} else if (mode == MODE_CATCHOUTPUT) {
System.out.println("catching output");
BufferedReader procout = new BufferedReader(
new InputStreamReader(pr.getInputStream())
);
String line;
while ((line = procout.readLine()) != null) {
System.out.println(" OUT> " + line);
}
}
try {
System.out.println(
"done, return value is " + pr.exitValue()
);
} catch (IllegalThreadStateException e) {
System.out.println(
"ok, process is running asynchronously"
);
}
}
private static void runShellCommand(String cmd, int mode)
throws IOException
{
String prefix = "";
String osName = System.getProperty("os.name");
osName = osName.toLowerCase();
if (osName.indexOf("windows") != -1) {
if (osName.indexOf("95") != -1) {
prefix = "command.com /c ";
} else if (osName.indexOf("98") != -1) {
prefix = "command.com /c ";
}
}
if (prefix.length() <= 0) {
System.out.println(
"unknown OS: don\'t know how to invoke shell"
);
} else {
runCommand(prefix + cmd, mode);
}
}
public static void main(String[] args)
{
try {
if (args.length <= 0) {
System.out.println(
"Usage: java RunCommand [-shell] " +
"[-waitfor|-catchoutput] <command>"
);
System.exit(1);
}
boolean shell = false;
int mode = MODE_UNCONNECTED;
String cmd = "";
for (int i = 0; i < args.length; ++i) {
if (args[i].startsWith("-")) {
if (args[i].equals("-shell")) {
shell = true;
} else if (args[i].equals("-waitfor")) {
mode = MODE_WAITFOR;
} else if (args[i].equals("-catchoutput")) {
mode = MODE_CATCHOUTPUT;
}
} else {
cmd = args[i];
}
}
if (shell) {
runShellCommand(cmd, mode);
} else {
runCommand(cmd, mode);
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
|