Reputation: 301
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
Upvotes: 2
Views: 1498
Reputation: 116
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();
Upvotes: 0
Reputation: 201429
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);
Upvotes: 1