iamjc015
iamjc015

Reputation: 2245

Running java programs inside a java program

Hi guys I want to run java programs inside my javaprogram.

However when I tried to execute java command it tells me this:

java c:\works\Sample stderr: Error: Could not find or load main class c:\works\Sample

This is my code:

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
        Processor p = new Processor();
        try {
            int k = p.runProcess("javac c:\\works\\Sample.java");
            if (k == 0) {       
                k = p.runProcess("java c:\\works\\Sample");
            }

            System.out.println("Value of k: " + k);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }      

This is my Processor Class

public class Processor {

public void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(
            new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
        System.out.println(name + " " + line);
    }
}

public int runProcess(String command) throws Exception {


    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    // System.out.println(command + " exitValue() " + pro.exitValue());
    return pro.exitValue();
}

}

My files were under "C:\works\"

Your responses would be greatly appreciated!

Upvotes: 2

Views: 268

Answers (1)

Izold Tytykalo
Izold Tytykalo

Reputation: 719

You can do this by having one master program which you run from your CMD which runs whatever processes you want and redirect input/output of these processes to its own input/output which happens to be your CMD input/output. Here is good example.

Upvotes: 1

Related Questions