本例使用 runtime.exec方法执行外部命令,在本例中执行外部的javac,java命令还有ping命令
Process封装了执行外部命令情况的信息,我们可以获取错误流或者输入流获取外部命令执行情况,
当然我们也可以获取输入流,写入命令执行信息。
package three.day.util.my;
import java.io.IOException;
import java.io.InputStream;
public class RuntimeProcessTs {
private static boolean isSuc = false;
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();//获取Runtime对象
String fileName = "hello";
javac(runtime,fileName);
if(isSuc){
java(runtime,fileName);
}
}
//编译一个外部.java源文件,该文件放置在Java Se工程的工程目录下,Se工程使用的相对路径一般都是以这个为相对路径的
.//只有类装载器或者applet获取资源时才是以bin目录为相对路径的
private static void javac(Runtime runtime, String fileName) {Process process = null;
try {
process = runtime.exec("javac " + fileName+".java");//执行外部命令 javac hello.java
InputStream is = process.getInputStream(); //通过process对象获取输入流获取命令成功执行情况
InputStream err = process.getErrorStream(); //通过process对象获取错误流获取命令出错情况
int len = 0;
byte[] buffer = new byte[1024];
while((len=err.read(buffer))!=-1 || (len=is.read(buffer))!=-1){//命令要么执行成功,要么执行失败,无论怎样我都把命令执行情况信息打印出来
System.out.print(new String(buffer));
}
isSuc = true;
} catch (IOException e) {
System.out.println("编译失败");
}finally{
process.destroy();
}
}
private static void java(Runtime runtime, String clazzName) {
Process process = null;
try {
process = runtime.exec("java " + clazzName);// java hello
InputStream is = process.getInputStream();
InputStream err = process.getErrorStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=err.read(buffer))!=-1 || (len=is.read(buffer))!=-1){
System.out.print(new String(buffer));
}
} catch (IOException e) {
System.out.println("运行失败");
}finally{
process.destroy();
}
}
private static void ping() {
Process process = null;
try {
Runtime runtime = Runtime.getRuntime();
process = runtime.exec("ping 8.8.8.8");//执行ping命令
InputStream is = process.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
System.out.print(new String(buffer));
}
} catch (IOException e) {
e.printStackTrace();
}finally{
process.destroy();//销毁process对象
}
}
}