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 - 我想让一个文本字段只有在 Netbeans 中选中一个复选框时才可编辑

java - Apache POI :- Get Headings from DOC file

Java 重新着色 JProgressBar 一根像素线

java - 调用其他有界上下文的策略

java - 从 Java 配置文件中读取配置参数的最佳方法是什么?

c++ - 有操作系统和没有操作系统的两个空 main{} 程序有什么区别?

java - 运算符|| Android 应用程序中的参数类型 java.lang.String、java.lang.String 未定义

python - Python和Pygame:运行时意外崩溃

java - 如何在运行时将 rhino/javascript 文件编译为 java 的 .class 字节码

java - 从 Java 运行 Linux 命令 - runtime.exe