Java runtime exec 不能很好地处理字符串数组

Java runtime exec not handling string array well

我有一个 tomcat servlet,它调用带有参数的 jar 函数。第一个参数有时包含space。所以我尝试使用 String 数组,但它根本不起作用。

我做错了什么?

requestParm = "java -classpath c:\j\test.jar test.connect " + fileName + " new";
requestParmarray =new String[]{"java -classpath c:\j\test.jar test.connect ",fileName , " new"};
requestParmarrayNew =new String[]{"java -classpath c:\j\test.jar test.connect "+fileName+" new"};

// This line works.but can not handle space well
Process ls_proc = Runtime.getRuntime().exec(requestPar);

// Does not call the function at all
Process ls_proc = Runtime.getRuntime().exec(requestParmarray ); 

// Does not call the function at all
Process ls_proc = Runtime.getRuntime().exec(requestParmarrayNew ); 

// Does not call the function at all
Process ls_proc = new ProcessBuilder("java -classpath c:\j\test.jar test.connect ",fileName, "new" ).start();

您创建的数组不正确:每个单独的参数都必须在其自己的条目中:

String[] requestParmArray = new String[] {
    "java",
    "-classpath",
    "c:\j\test.jar",
    "test.connect",
    fileName,
    "new"
};
Process ls_proc = Runtime.getRuntime().exec(requestParmArray);

另请注意,我删除了您在 test.connect 之后的 space;你放在命令行上的 spaces 只是为了分隔参数,但在上面,它们是通过数组中的单独条目分隔的。

您应该使 exec() 中的数组将每个参数作为单独的数组条目,例如:

String[] requestPar = new String[]{"java", "-classpath", "c:\j\test.jar", "test.connect ", fileName, "new"};

并使用它:

Process ls_proc = Runtime.getRuntime().exec(requestPar);