Gili
Gili

Reputation: 90111

How to get ProcessBuilder to handle nested quotes?

I am having problems getting ProcessBuilder to execute a command-line the same way as the cmd.exe console.

  1. The command line is: show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\""
  2. The batch file show_parameters.bat (below) shows the tokens that cmd.exe breaks the command-line into.
  3. Testcase.java (below) attempts to execute the same command-line as #1 using ProcessBuilder.
  4. If you run show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v"/qn INSTALLDIR=\"C:\Program Files (x86)\gili\"" you will get:

    Console tokens:
    
    jdk-1_5_0_22-windows-i586-p.exe
    /s
    /v"/qn INSTALLDIR=\"C:\Program
    Files
    (x86)\gili\""
    
  5. If you run java Testcase you will get:

    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\"
    ""
    

Is it possible to cause ProcessBuilder to produce the same tokenization as #1? Or is this a bug in 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);
        }
    }
}

Upvotes: 2

Views: 1746

Answers (1)

stan
stan

Reputation: 1014

Try that way:

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "show_parameters.bat jdk-1_5_0_22-windows-i586-p.exe /s /v\"/qn INSTALLDIR=\\\"" + base + "\\\"\"");

or

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" is expecting one argument only - the command which will be executed in the CMD

Upvotes: 2

Related Questions