我在让ProcessBuilder以与 cmd.exe 控制台相同的方式执行命令行时遇到问题。
- 命令行是:
show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""
- 批处理文件
show_parameters.bat
(如下)显示了 cmd.exe 将命令行分解为的标记。 Testcase.java
(下)尝试使用 ProcessBuilder 执行与 #1 相同的命令行。如果你跑步
show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""
,你会得到:Console tokens: jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""
如果你跑步
java Testcase
,你会得到:Java tokens: [cmd.exe, /c, show_parameters.bat, jdk-1_5_0_22-windows-i586-p.exe, /s, /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""] Console tokens: jdk-1_5_0_22-windows-i586-p.exe /s "/v"/qn INSTALLDIR \"C:\Program Files (x86)\gili\" ""
是否有可能使 ProcessBuilder 产生与 #1 相同的标记化?或者这是Java中的错误?
show_parameters.bat
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
echo.
echo Console tokens:
echo.
:again
if [%1] == [] goto end
echo %1
shift
goto again
:end
测试用例.java
import java.io.*;
public class Testcase
{
public static void main(String[] args) throws IOException, InterruptedException
{
String base = "C:\\Program Files (x86)\\gili";
ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "show_parameters.bat", "jdk-1_5_0_22-windows-i586-p.exe", "/s",
"/v\"/qn INSTALLDIR=\\\"" + base + "\\\"\"");
processBuilder.redirectErrorStream(true);
System.out.println("Java tokens: " + processBuilder.command());
Process process = processBuilder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
while (true)
{
String line = in.readLine();
if (line == null)
break;
System.out.println(line);
}
}
}