如何执行从txt文件检索的Java代码? [英] How can I execute java code retrived from txt file?

查看:91
本文介绍了如何执行从txt文件检索的Java代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件(example.txt),其中包含以下Java代码"System.out.println("H​​ello World!");

I have a text file(example.txt) that contains this java code "System.out.println("Hello World!");

如何执行从文本文件中检索到的Java代码?

How can I execute this java code retrieved from the text file?

谢谢:x

推荐答案

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

You can create class read from this file example.txt and write in tmp java file and access this tmp file from any java code

首先创建和Test.java类

First create and Test.java class

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

以此类为例.文本字符串将以执行方式写入

int this class example.text strings will write in excute method te be executed

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

Then write javac ExcuteStringCode.java Then write java ExcuteStringCode

这篇关于如何执行从txt文件检索的Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆