我有一个 tomcat servlet,它使用参数调用 jar 函数。第一个参数有时包含空格。所以我尝试使用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
之后的空格;您在命令行上放置的空格只是为了分隔参数,但在上面,它们通过数组中的单独条目来分隔。
关于Java运行时exec不能很好地处理字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37936322/