Init
Runtime.getRuntime()
is the only method can get jvm runing environment- Most method in Runtime is implements method
- Runtime.exit() is the only method exit current jvm.
System.exit()
0
represent normal execute, !0
represent exceptionRuntime.addShutdownHook()
can recieve a thread object as a handlepublic Process exec(String[] cmdarray, String[] envp, File dir)
when sub process use current process environment variable, envp is null.
Call
1 | Process proc = Runtime.getRuntime().exec("java"); |
Process call exitValue is not block, if needed add a loop call
1 | Process proc = Runtime.getRuntime().exec("java"); |
correct call process need set process’s stream setting, make sure thread will not block.
1 | Process proc = Runtime.getRuntime().exec("java hello > hi"); |
in command line can’t execute bash sign like >
>>
<
&
.
1 | Process proc = Runtime.getRuntime().exec( |
if need these local operation, you can write these in a shell script, or load bash in java.
Call in windows
if you want call in windows you need install bash first1
2
3
4Process proc = Runtime.getRuntime().exec(
new String[]{"D:\\Program Files\\Git\\bin\\sh.exe", "-c", command}, null, null);
// add stream setting
int exitVal = proc.waitFor();
if jvm execute path is not the exec
path, you need add specific path1
2
3
4Process proc = Runtime.getRuntime().exec(
new String[]{"D:\\Program Files\\Git\\bin\\sh.exe", "-c", command}, null, new File(workPath));
// add stream setting
int exitVal = proc.waitFor();
ps. -c
mean read parameter in string format, not directly %0 %1
Another way
If you want jvm do standard in /out, use another thread read or write data1
2
3
4
5Process proc = Runtime.getRuntime().exec("java hello");
// add pip stream thread setting
StreamThread director = new StreamThread(proc.getInputStream(),proc.getOutputStream());
director.start();
int exitVal = proc.waitFor();
https://blog.csdn.net/mengxingyuanlove/article/details/50707746
https://blog.csdn.net/timo1160139211/article/details/75006938