Reputation: 2619
I have written a command line script and I am testing that using java
.
In command line I write like this: script -html="anchor bold"
so while testing the same using java code, how exactly should my string be outlined?
-html=anchor bold"
it doesn't work as double quotes dont get included so my test fails
-html=\"anchor bold\"
this escapes double quotes but I want it.
-html=\\\"anchor bold\\\"
this results in -html=\"anchor bold\"
but I don't want any slashes.
I am using a String[]
array to execute the command.
new String[] { "--path=" + p,
"--user=" + user,
"--html=\"anchor bold\"",
"--port=8081"
}
The command line argument is:
path/executeScript --path=path1 --user=testUser --html="anchor bold" --port=8081
Upvotes: 1
Views: 3593
Reputation: 31
Use the escape character in front of anything you want to use as a literal character, then put the double quotes around it as usual.
script -html="\"anchor bold\""
Upvotes: 2
Reputation: 3863
A way I could think of.. Using characters.
"--html=" + '"' + "anchor bold" + '"'
Upvotes: 0
Reputation: 16833
If you want to to test your script with Java, with parameters containing quotes, you don't have any choice, you'll have to escape it.
String[] command = new String[] {
"path/executeScript",
"--path=" + p,
"--user=" + user,
"--html=\"anchor bold\"",
"--port=8081"
}
Runtime.getRuntime().exec(command);
Technical explanation : https://stackoverflow.com/a/3034195/2003986
Upvotes: 11
Reputation: 11041
To declare a String literal, the only way to do it is with double quotes surrounding characters in the String. Like this:
"String Characters"
... String Characters
From the Java Language Specifications §3.10.5
:
A string literal consists of zero or more characters enclosed in double quotes. Characters may be represented by escape sequences (§3.10.6) - one escape sequence for characters in the range U+0000 to U+FFFF, two escape sequences for the UTF-16 surrogate code units of characters in the range U+010000 to U+10FFFF.
See §3.10.6 for the definition of EscapeSequence.StringLiteral: " {
StringCharacter} " StringCharacter: InputCharacter but not " or \ EscapeSequence
[...]
The following are examples of string literals:"" // the empty string "\"" // a string containing " alone "This is a string" // a string containing 16 characters "This is a " + // actually a string-valued constant expression, "two-line string" // formed from two string literals
Because escaping the double quotes is a compile-time syntax requirement, you must escape the double quotes in a String literal.
You can try for a Unicode literal, but I highly doubt (spoilers: it doesn't) the compiler would accept it:
"--html=\u0022anchor bold\u0022"
— Wrong
Use an escape:
"--html=\"anchor bold\""
— Right
Of which is treated by the compiler as:
... --html="anchor bold"
See also:
Upvotes: 4