package file_review;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//获取进程数据-编译和运行Java代码
public class ProcessDemo {
public static void main(String[] args) throws Exception {
String str = "System.out.println(\"坚持就是胜利!\");";
eval(str);
}
private static void eval(String str) throws Exception {
//拼接字符串内容为可执行的.java文件
StringBuilder sb = new StringBuilder(100);
sb.append("public class Hello{\n");
sb.append("\tpublic static void main(String[] args){\n\t\t");
sb.append(str + "\n");
sb.append("\t}\n");
sb.append("}");
System.out.println(sb);
//将字符串以指定名字写到指定位置
File destFile = new File("D:/workspcae/listAllFiles/process/Hello.java");
OutputStream out = new FileOutputStream(destFile);
out.write(sb.toString().getBytes());
out.close();
//通过Runtime类开启新的进程并执行指令
Process javacProcess = Runtime.getRuntime().exec("cd /d D:/workspcae/listAllFiles/process && javac Hello.java");
//Runtime类返回的Process 调用其getErrorStream()方法 并读进来打印
InputStream error = javacProcess.getErrorStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = error.read(buffer)) != -1) {
System.out.println(new String(buffer));
}
error.close();
Process javaProcess = Runtime.getRuntime().exec("cd /d D:/workspcae/listAllFiles/process && java Hello");
InputStream in = javaProcess.getErrorStream();
while ((len = in.read(buffer)) != -1) {
System.out.println(new String(buffer));
}
in.close();
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
//获取进程数据-编译和运行Java代码
public class ProcessDemo {
public static void main(String[] args) throws Exception {
String str = "System.out.println(\"坚持就是胜利!\");";
eval(str);
}
private static void eval(String str) throws Exception {
//拼接字符串内容为可执行的.java文件
StringBuilder sb = new StringBuilder(100);
sb.append("public class Hello{\n");
sb.append("\tpublic static void main(String[] args){\n\t\t");
sb.append(str + "\n");
sb.append("\t}\n");
sb.append("}");
System.out.println(sb);
//将字符串以指定名字写到指定位置
File destFile = new File("D:/workspcae/listAllFiles/process/Hello.java");
OutputStream out = new FileOutputStream(destFile);
out.write(sb.toString().getBytes());
out.close();
//通过Runtime类开启新的进程并执行指令
Process javacProcess = Runtime.getRuntime().exec("cd /d D:/workspcae/listAllFiles/process && javac Hello.java");
//Runtime类返回的Process 调用其getErrorStream()方法 并读进来打印
InputStream error = javacProcess.getErrorStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = error.read(buffer)) != -1) {
System.out.println(new String(buffer));
}
error.close();
Process javaProcess = Runtime.getRuntime().exec("cd /d D:/workspcae/listAllFiles/process && java Hello");
InputStream in = javaProcess.getErrorStream();
while ((len = in.read(buffer)) != -1) {
System.out.println(new String(buffer));
}
in.close();
}
}