user3468728 user3468728 - 11 months ago 123
Java Question

How to run .class file programmatically in java from another .java file

My Question is that I have a .class file(first servlet program after compilation) which is compiled using netbeans(apache tomcat as server) and have another .java file(second servlet program). I delete .java file of my first servlet program and keep its .class file only.Now from second servlet program , I want to execute .class file of first servlet program and also pass some parameters to my .class file(first servlet program after compilation).

I have googled lot on the internet.It shows use reflection or use something like this :

Process theProcess = re.exec("java -cp C: /java/abc.class");

But I am unable to solve this problem.


In order to run another program try:

 ProcessBuilder builder = new ProcessBuilder("java", "SecondApplication"); //without .class suffix File("C:\\Users\\etc")); //I don't know you're on linux or windows. Just go to where your "SecondApplication" is located.
 Process process = builder.start();

 OutputStream pIn = process.getOutputStream();
 InputStream pOut = process.getInputStream();

 BufferedReader reader = new BufferedReader(new InputStreamReader(pOut));
 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(pIn));

Now you have all you need to interact with your second application. You can write to its standard input stream using writer and read its output using reader.