0

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

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

Thanks :x

Adam
  • 49
  • 1
  • 8
  • @Newble i have one doubt regarding your example.txt file have any main class. – Sathiyaraj Mar 13 '14 at 09:55
  • 1
    as far as I know, java is a static language, your code is not complete, so it cannot compile and execute... – longkai Mar 13 '14 at 09:55
  • You can't do that. The only thing i can imagine is that you parse an entire class and store it somewhere so you could run that class later. But I'm not sure if you can load this file. – Klemens Morbe Mar 13 '14 at 09:57

1 Answers1

0

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

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();
    }
}

}

Then write javac ExcuteStringCode.java Then write java ExcuteStringCode

B.Abouads
  • 20
  • 4