2

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

Community
  • 1
  • 1
APCoding
  • 303
  • 2
  • 19

2 Answers2

1

You can add them to the ProcessBuilder(String...) constructor call (in your case after the className) like

ProcessBuilder builder = new ProcessBuilder(
 javaBin, "-cp", classpath, className, args);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • What if I have multiple args? – APCoding Jun 26 '15 at 23:51
  • @APCoding If you have multiple args you can pass them. `String...` is a `String` [varargs](http://docs.oracle.com/javase/7/docs/technotes/guides/language/varargs.html) type. `javaBin, "-cp", classpath, className, "1", "2", "3"` – Elliott Frisch Jun 26 '15 at 23:54
0

You can use it just like this:

ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(rootPath));
List<String> command = new ArrayList<String>();
command.add("java");
command.add(String.format("-XX:MaxPermSize=%sm", 512));
command.add("-jar");
command.add(jarName);
command.add("parameter1=123");
command.add("parameter2=456");
pb.command(command);
Process process = pb.start();
Xinyuan.Yan
  • 116
  • 1
  • 7