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

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

What if I have multiple args?
@APCoding If you have multiple args you can pass them. String... is a String varargs type. javaBin, "-cp", classpath, className, "1", "2", "3"
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.