2

我在让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. 批处理文件show_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

测试用例.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);
        }
    }
}
4

1 回答 1

2

试试这样:

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 中执行的命令

于 2013-09-17T08:37:39.747 回答