用字符串写一段伪代码,然后写入一个java文件,再调用进程编译
//调用javac进程
Process p = Runtime.getRuntime().exec("javac Hello.java");
//调用java进程
Process p1 = Runtime.getRuntime().exec("java Hello");
示例代码
package com.java520.iodemo01;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class PersonDemo
{
public static void main(String[] args) throws Exception
{
//写文件
writeFile();
//获取进程并运行
getProcess();
}
private static void getProcess() throws Exception {
// TODO Auto-generated method stub
//1.调用javac 进程来编译Hello.java
Process p = Runtime.getRuntime().exec("javac Hello.java");
//2.有可能编译出错,所以需要获取一下编译后的流来得知编译信息
InputStream errorStream = p.getErrorStream();
byte[] b = new byte[1024];
int ln = -1;
while ((ln = errorStream.read(b)) != -1){
String str = new String(b,0,ln);
System.out.println(str);
}
//3.关闭资源
errorStream.close();
//4.调用java进程来编译Hello.class
Process pjava = Runtime.getRuntime().exec("java Hello");
//5.获取java进程中的的流信息
InputStream infoStream = pjava.getInputStream();
byte[] bjava = new byte[1024];
int ln1 = -1;
while((ln1 = infoStream.read(bjava)) != -1){
String str = new String(bjava,0,ln1);
System.out.println(str);
}
//6.关闭资源
infoStream.close();
//7.删除文件
new File("Hello.java").delete();
new File("Hello.class").delete();
}
private static void writeFile() throws Exception{
// TODO Auto-generated method stub
StringBuilder str = new StringBuilder();
str.append("public class Hello{");
str.append("public static void main(String[] args){");
str.append("System.out.println(\"你是我天边最美的云彩\");");
str.append("}");
str.append("}");
//创建输出对象
File file = new File("Hello.java");
//创建输出流
OutputStream out = new FileOutputStream(file);
//输出
out.write(str.toString().getBytes());
//关闭
out.close();
}
}