如何让ProcessBuilder处理嵌套的引号?

我遇到的问题是让ProcessBuilder执行命令行的方式与cmd.exe控制台相同。

  1. 命令行是: show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""
  2. batch fileshow_parameters.bat (下面)显示了cmd.exe将命令行分成的标记。
  3. Testcase.java (以下)尝试使用ProcessBuilder执行与#1相同的命令行。
  4. 如果你运行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\"" 
  5. 如果你运行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 

Testcase.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); } } } 

尝试这种方式:

 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 processBuilder = new ProcessBuilder("cmd.exe", "/c", "show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v\"/qn INSTALLDIR='" + base + "'\""); 

“/ c”只需要一个参数 – 将在CMD中执行的命令