如何执行从txt文件中检索的java代码?

时间:2014-03-13 09:51:43

标签: java file

我有一个包含此java代码的文本文件(example.txt)" System.out.println(" Hello World!");

如何执行从文本文件中检索的此java代码?

谢谢:x

1 个答案:

答案 0 :(得分:0)

您可以从此文件example.txt创建类读取并在tmp java文件中写入并从任何Java代码访问此tmp文件

首先创建和Test.java类

public class Test{
public static void excute(){
}
}

int此类example.text字符串将在执行方法中执行

public class ExcuteStringCode {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    try {
        System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_21");
        BufferedReader br=new BufferedReader(new FileReader("d:\\example.txt"));
        PrintWriter writer=new PrintWriter("d:\\Test.java");
        writer.write("public class Test{\n");
        writer.write("public static void excute(){\n");
        String reader="";
        System.out.println("start");
        while((reader=(br.readLine()))!=null){
            writer.write(reader+"\n");
        }
        writer.write("}\n}");

        br.close();
        writer.close();

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        System.out.println(compiler);
        int b=compiler.run(null, null, null,"d:\\Test.java");
        Test testme=new Test();
        testme.excute();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

然后编写javac ExcuteStringCode.java 然后编写java ExcuteStringCode