The goal of my project is to execute user entered Java code from the mobile device.
So far I have been able to take in the code that the user types in from the EditText and insert it into a .java file in the data/ folder of the device.
I now stuck on compiling that .java file from within the device into a .class so that I can then turn the .class into a .dex and execute the method containing the user's code.
Here is the code to which i use to create the .java file. For this example, I have created a string to represent a user input, but in the application it would be taken from an EditText box:
writeJavaFile("public class UserClass{public void userMethod(){\n\n\n\n}}");
insertUserCode("System.out.println(\"This is a print\")");
private void insertUserCode(String userData){
try{
File file = new File(getFilesDir(),"TestClass.java");
BufferedReader br = new BufferedReader(new FileReader(file));
StringBuilder text = new StringBuilder();
String line;
int counter = 0;
while((line = br.readLine()) != null) {
if(counter == 2){
text.append(userData);
}else{
text.append(line);
}
counter++;
}
br.close();
writeJavaFile(text.toString());
}catch(Exception e){
e.printStackTrace();
}
}
private void writeJavaFile(String stringToInsert) {
try{
FileOutputStream fOut = openFileOutput("TestClass.java", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(stringToInsert);
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace();
}
}