Run cmd script with double quotes

I am trying to execute Processwith multiple parameters, but they have double quotes "...".

This is how I create the script:

public void capture(String from, String to, String outputFile)

This method will run the command, it takes three parameters, which are given here:

capture("0", "100", "C:\\Program Files\\myProgram\\file.txt")

So, the full built-in command looks like this:

String command = "\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis "
    + from + " " + to + " \"" + outputFile + "\"";

To make this clear, this is the visual output of the command:

"C:\Program Files (x86)\otherProg\prog.exe" /dothis 0 100 "C:\Program Files\myProgram\file.txt"

Ok, and then I execute it as follows:

String[] script = {"cmd.exe", "/c", command};
Process p = Runtime.getRuntime().exec(script);

And at this moment nothing happens.
The command will not be executed, however , if I take the output:

"C:\Program Files (x86)\otherProg\prog.exe" /dothis 0 100 "C:\Program Files\myProgram\file.txt"

Copy-paste it into the CMD, the DOES command will be executed (and I will get the expected result).

, , .
- :

"C:\Program Files (x86)\otherProg\prog.exe" /dothis 0 100 C:\Folder\myProgram\file.txt

, , .

?

1:
script = script.replace("\n","").replace("\t","") .

2:
:

Process p = Runtime.getRuntime().exec(
    "\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis 0 100 \"C:\\Program Files\\myProgram\\file.txt\"");

escape- , , ?


, java , , , :

String command = "cd \"C:\\Program Files (x86)\\otherProgram\\\" & program.exe /capture "+from+" "+to+" \""+outputFile+"\"";    

& .

+4
2

. :

Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe echo Hello World");

( ), echo. , :

Process p = Runtime.getRuntime().exec("cmd /c start cmd.exe blah blah blah");

, , Java , cmd.exe. , start, - cmd.exe. , Java , , .

, :

Process p = Runtime.getRuntime().exec(
"\"C:\\Program Files (x86)\\otherProg\\prog.exe\" /dothis 0 100 \"C:\\Program Files\\myProgram\\file.txt\"");

prog.exe, , . , , .

, , Runtime.getRuntime().exec() Java, . , Java , API .

+3

/

Process Builder

ProcessBuilder pb = new ProcessBuilder("\"C:\\Program Files (x86)\\otherProg\\prog.exe\"", "/dothis ", "from + " " + to + " \"" + outputFile + "\"");
Process p = pb.start();

Runtime.getRuntime().exec(new String[]{"\"C:\\Program Files (x86)\\otherProg\\prog.exe\"", "/dothis ", "from + " " + to + " \"" + outputFile + "\""});
0

Source: https://habr.com/ru/post/1625085/


All Articles