0

Let's say I have code inside a PLAIN TEXT FILE:

File f = new File("file.txt");
try{
    BufferedReader reader = new BufferedReader(new FileReader(f));
    String line = reader.readLine();
    System.out.println(line);
    }catch(IOException e){
        e.printStackTrace();
    }

Is there a way I can perform that code, and if so, how? i.e. my application would have a method that would read the file, and actually do the code. Is there a way to do this?

The code inside the file is read by my application. I then want to execute this code as if it is a compiled java program.

JD9999
  • 394
  • 1
  • 7
  • 18

1 Answers1

1

What code is contained in the file.txt? Does 'perform' it mean 'run'?

If the code contained is a valid java code (including imports, full class def etc), then you can use java compiler API.

Once you compile it, running it is easy, since you can either invoke java process with the generated class or load the generated class dynamically, and run the method using reflection.

JackDaniels
  • 985
  • 9
  • 26