I have two Java programs, called A and B. A looks like this
Scanner deusex = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
String again = "Y";
while (again == ("Y"))
{
out.println("Enter a string.");
String user1 = deusex.next();
list.add(user1);
out.println("Input again? [Y/N]");
again = deusex.next();
if (again.equalsIgnoreCase("Y"))
again = "Y";
}
out.println("Your elements: " + list);
out.println("Delete elements? [Y/N]");
String y = deusex.next();
if (y.equalsIgnoreCase("y"))
{
String again1 = "Y";
out.println("Printing outputs...");
out.println(list);
while (again1 == ("Y"))
{
out.println("Enter index of element to delete [0,1,2...]");
int user3 = deusex.nextInt();
list.remove(user3);
out.println("Printing outputs...");
out.println(list);
out.println("Input again? [Y/N]");
again = deusex.next();
if (again.equalsIgnoreCase("Y"))
again1 = "Y";
else System.exit(0);
}
}
else { out.println("Bye."); };
}
}
I have uploaded A in a .txt file to google drive. My program B is written to download the file then save it as a .java file. I then compile it and try to run it. This is the part of code B that is important:
System.out.println("Enter anything to compile and run.");
String anything1 = Gooch.next();
String line = null;
try
{
Process pleasecompile = new ProcessBuilder("javac", "A.java").start();
Process pleaserun = new ProcessBuilder("java", "A").start();
BufferedReader input = new BufferedReader(new InputStreamReader(pleaserun.getInputStream()));
BufferedWriter output= new BufferedWriter(new OutputStreamWriter(pleaserun.getOutputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
output.write(300);
}
pleaserun.waitFor();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Running this code for B only prints out the first line of A. I want to be able to run A in its entirety and get and give inputs and outputs. I figured out so far that I need to manipulate the buffered readers with some loops or processes to do this, but I have no idea how.
I know that if I just compile A.java with Process pleasecompile I can directly call the class afterwards using something like A.main(String[0]);. The issue is that the A.class file does not exist at compile time, only after being downloaded and compiled itself, so my B program gives me a cannot find symbol error for A.main when compiling. My question is whether I can set something up that will call the class for me after compiling A in B without the error, if not resorting to manipulating the readers.
My suggestion is to use reflection. As per the code class B can compile and run. When B runs, the pleaseCompile method will compile the class A. why don't you go for reflection that is used to load a class at runtime.
You can probably visit this link tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html fir tutorials on reflection