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
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
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