gpt4 book ai didi

java - 在java中写入.java文件并运行脚本

转载 作者:行者123 更新时间:2023-12-01 22:38:24 25 4
gpt4 key购买 nike

我目前正在尝试用 Java 编写一个 .java 文件。我有一些类 Driver 调用我的子类 Eval:

public class Driver
{
public static void main(String[] args)
{
Eval eval = new Eval();
eval.evaluate("System.out.println(\"Hello!!! I'm an auto-generated .java file!);\");
}
}

这是我的 Eval 类(存储在同一项目中):

public class Eval
{
public Eval()
{

}

public void evaluate(String toEval)
{
PrintWriter writer = new PrintWriter("Auto.java", "UTF-8");
writer.println("public class Auto");
writer.println("{");
writer.println(" public static void main(String[] args)");
writer.println(" {");
writer.println(" " + toEval;
writer.println(" }");
writer.println("}");
writer.close();
}
}

因此,我在同一目录中手动创建 Auto.java 类。我运行脚本,查看 Auto.java,令我惊讶的是,什么也没有写!

public Auto
{
}

(这就是我手动创建它后留下的方式)
如有任何建议,我们将不胜感激。
谢谢!

附注此外(尽管上述错误优先于这个问题),我如何从 Eval 类运行这个程序?

最佳答案

试试这个:

 /**
* @author Rustam
*/
public class Test {


public static void main(String[] args) throws FileNotFoundException,
UnsupportedEncodingException {

Eval eval = new Eval();
eval.evaluate("System.out.println(\"Hello!!! I'm an auto-generated .java file!\")");
try {
runProcess("javac Auto.java");
runProcess("java Auto");
} catch (Exception e) {
e.printStackTrace();
}

}

private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}

private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(name + " " + line);
}
}
}

class Eval
{
public Eval()
{

}

public void evaluate(String toEval) throws FileNotFoundException, UnsupportedEncodingException
{
PrintWriter writer = new PrintWriter("Auto.java", "UTF-8");
writer.println("public class Auto");
writer.println("{");
writer.println(" public static void main(String[] args)");
writer.println(" {");
writer.println(" " + toEval + ";");
writer.println(" }");
writer.println("}");
writer.close();
System.out.println("Auto.java created..");
}
}

输出:

Auto.java created..
javac Auto.java exitValue() 0
java Auto stdout: Hello!!! I'm an auto-generated .java file!
java Auto exitValue() 0

关于java - 在java中写入.java文件并运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com