Java运行时exec不能很好地处理字符串数组

标签 java runtime

我有一个 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/

相关文章:

Java-eclipse-获取.exe文件

java - Eclipse Mars Java - 首选项错误 - 无法接受更改

java - iText:从 HTML 创建短语

c++ - 如何在 Eclipse 和 Linux 上介入代码实现 new()?

flash - OpenLaszlo 的双运行时方法(HTML5 和 Flash/SWF)是否仍然有效?

gradle - 添加gradle war空 jar

java - 使用包编译Java项目

java - 如何解决加载 spring-context 的问题?

java - 运行外部程序

java - 获取方法参数的名称