Java starting a seperate process and attaching args

76 views Asked by At

When starting a separate process which runs a program called Program.java, I was wondering how I could add args to this. For those of you who don't know, args are the things you see at the start of lots of Java programs: public static void main(String[] args) I know when you run a .class file from the terminal, you type java [program name] [args]. So how do I add args when starting a separate process? My code:

Class klass=Program.class;
String[] output=new String[2];
String javaHome = System.getProperty("java.home");
String javaBin = javaHome +
     File.separator + "bin" +
     File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = klass.getCanonicalName();

ProcessBuilder builder = new ProcessBuilder(
     javaBin, "-cp", classpath, className);
builder.redirectErrorStream(true);

Process process = builder.start();
int in = -1;
InputStream is = process.getInputStream();
String[] outputs=new String[2];
try {
    while ((in = is.read()) != -1) {
       outputs[0]=outputs[0]+(char)in;
    }
} catch (IOException ex) {
    ex.printStackTrace();
}
builder.redirectErrorStream(true);
try {
    while ((in = is.read()) != -1) {
           outputs[1]=outputs[1]+(char)in;
    }
} catch (IOException ex) {
    ex.printStackTrace();
}
int exitCode = process.waitFor();
System.out.println("Exited with " + exitCode);

This differs from this question because my question uses ProcessBuilder to create the process.

Thanks

1

There are 1 answers

0
Adam On BEST ANSWER

"args" are simply the command line arguments after the initial JVM switches like -cp, and -D parameters and entry point class.

The following will start a new JVM process which will load org.example.MainProgram and pass it [arg0, arg1, arg2] as the args array.

java -cp bin/* org.example.MainProgram arg0 arg1 arg2

So in your example, simply add arguments to the end of the ProcessBuilder constructor

ProcessBuilder builder = new ProcessBuilder(
      javaBin, "-cp", classpath, className, "arg0", "arg1", "arg2");

There is also an alternative strategy you could use if launching a Java app from another Java app. This won't allow you to capture standard output, but if you control both apps I'd consider using an API to access the functionality of the launched app rather than communicating via streams, parsing etc...

new Thread(new Runnable() {
   @Override    
    public void run() {
       org.example.MainProgram.main(new String[]{"arg0", "arg1", "arg2"})
    }
}).start();