Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a .java file using ProcessBuilder

I'm a novice programmer working in Eclipse on Windows XP, and I need to get multiple processes running (this is going to be a simulation of a multi-computer system). My initial hackup used multiple threads to multiple classes, but now I'm trying to replace the threads with processes.

From my reading, I've gleaned that ProcessBuilder is the way to go. I have tried many many versions of the input you see below, but cannot for the life of me figure out how to properly use it. I am trying to run the .java files I previously created as classes (which I have modified). I eventually just made a dummy test.java to make sure my process is working properly - its only function is to print that it ran.

My code for the two files are below. Am I using ProcessBuilder correctly? Is this the correct way to read the output of my subprocess? Any help would be much appreciated.

  • David

Edit: The solution is to declare ProcessBuilder("java.exe","-cp","bin","Broker.test");

primary process

package Control;
import java.io.*;
import java.lang.*;

public class runSPARmatch {

/**
 * @param args
 */
public static void main(String args[]) {
    try {       
        ProcessBuilder broker = new ProcessBuilder("javac.exe","test.java","src\\Broker\\");
        Process runBroker = broker.start();

        Reader reader = new InputStreamReader(runBroker.getInputStream());
        int ch;
        while((ch = reader.read())!= -1)
            System.out.println((char)ch);
        reader.close();

        runBroker.waitFor();

        System.out.println("Program complete");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

subprocess

package Broker;

public class test {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("This works");
    }
}
like image 379
David K Avatar asked Apr 10 '12 17:04

David K


Video Answer


1 Answers

You are calling the java compiler on the .java file, this will not run the class. What you probably want to do is running java.exe on your .class file. (ie something like "java.exe -cp ./bin Broker.test", assuming your class files are in ./bin)

like image 170
Helmuth M. Avatar answered Oct 11 '22 17:10

Helmuth M.