java 调用命令行
JAVA Runtime类
1. exec以一个独立进程执行command,并返回Process句柄。
Process类说明: https://blog.youkuaiyun.com/zhoulupeng2012/article/details/49430455.
2. 当独立进程启动后,可以获取改进程的输出流和错误流。
– Process.getInputStream():可获取进程的输出流。
– Process.getErrorStream():可获取对象的错误输出流。
3. 调用Process.waitFor()方法等待目标进程终止。
java调用命令行
1. java调用终端,使用命令"javac"
import java.io.*;
public class JavaExec2 {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
//javac后无具体的参数,会输出错误信息。
Process p = rt.exec("javac");
//获取错误信息流。
InputStream stderr = p.getErrorStream();
//将错误信息流输出
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = "";
System.out.println("--------------error---------------");
while((line = br.readLine()) != null)
System.out.println(line);
System.out.println("");
//等待进程完成。
int exitVal = p.waitFor();
System.out.println("Process Exitvalue: " + exitVal);
}catch(Throwable t) {
t.printStackTrace();
}
}
}
由于javac后无具体的参数,会输出错误提示信息。
--------------error---------------
用法: javac <options> <source files>
其中, 可能的选项包括:
-g 生成所有调试信息
.........................................................省略好多行。
Process Exitvalue: 2
2. java调用终端,使用javac编译helloWorld.java文件
编写好的helloWorld.java文件放在此目录下:
/Users/kyan/Desktop/JAVA/Mooc/helloWord.java。
import java.io.*;
public class JavaExec3 {
public static void main(String[] args) {
Process p;
String[] cmds = new String[2];
cmds[0] = "javac";
cmds[1] = "/Users/kyan/Desktop/JAVA/Mooc/helloWord.java";
try {
//执行命令,将helloWord.java文件编译为.class文件
p = Runtime.getRuntime().exec(cmds);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while((line = br.readLine()) != null)
System.out.println(line);
System.out.println();
}catch(Exception e) {
e.printStackTrace();
}
}
}
3. java调用终端,使用java运行编译好的helloWorld.class文件
import java.io.*;
public class JavaExec4 {
public static void main(String[] args) throws InterruptedException {
Process p;
String[] cmds = new String[2];
cmds[0] = "java";
cmds[1] = "helloWord";
try {
//执行命令,运行helloWord.class文件。
p = Runtime.getRuntime().exec(cmds, null, new File("/Users/kyan/Desktop/JAVA/Mooc/"));
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = br.readLine()) != null)
System.out.println(line);
System.out.println();
int exitVal = p.waitFor(); //获取进程最后返回状态
System.out.println("Process exitValue: " + exitVal);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
hello world!
Process exitValue: 0