使用ProcessBuilder启动新进程时Java添加args

时间:2015-06-26 23:42:48

标签: java args

当启动一个运行名为Program.java的程序的单独进程时,我想知道如何为此添加args。对于那些不了解的人来说,args是你在许多Java程序开始时看到的东西:public static void main(String [] args)我知道当你从终端运行.class文件时,你输入java [program name] [args]。那么如何在启动单独的流程时添加args?我的代码:

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 question不同,因为我的问题使用ProcessBuilder来创建流程。

由于

2 个答案:

答案 0 :(得分:1)

您可以将其添加到ProcessBuilder(String...) constructor来电(在className之后的情况下)

ProcessBuilder builder = new ProcessBuilder(
 javaBin, "-cp", classpath, className, args);

答案 1 :(得分:0)

您可以像这样使用它:

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();