I know. There are several questions about it and you will say I must use ProcessBuilder and pass a String[] as parameters. But I REALY need to pass a quoted string to exec().
List<String> args = new ArrayList<String>();
args.add( "ogr2ogr" );
args.add( "-append" );
args.add( "-update" );
args.add( "-f" );
args.add( "PostgreSQL" );
args.add( "PG:\"host='odisseu-db' user='postgres' dbname='odisseu' password='guesswhat' port='5432'\"" );
args.add( file.getName() );
args.add( "-nlt" );
args.add( "GEOMETRY" );
Process process = new ProcessBuilder( args ).start();
As you can see, the PG parameter needs to be followed by a quoted string. I get an error like: "You dumb! I can't connect to the user='postgres' dataset! ". I'm sure the ogr2ogr is thinking I'm not quoting that parameter.
How can I escape this parameter?
EDIT Updated the parameters one by index. Still same problem.
1 Answer 1
Here's the problem. The handling of quotes in the Windows implementation of Java Process is a bit odd.
Any double-quote character that it sees is simply removed. If you want the double-quote to be passed through it has to be escaped with a backslash. And since you are using a Java String literal, the backslash also needs to be escaped.
So ... change the string to this:
"PG:\\\"host='odisseu-db' user='postgres' dbname='odisseu' password='guesswhat' port='5432'\\\""
Reference: https://bugs.openjdk.java.net/browse/JDK-8131908
But note the final comment from the reviewer:
"The reported behavior seems to be in line with this document https://msdn.microsoft.com/en-us/library/17w5ykft.aspx which describes, how the quotation marks are processed in Windows.
Closing this as 'not an issue'."
For Java on Linux, all characters in the argument strings are translated to the OS default character set and then passed straight through to the command. Single or double-quote characters have no special meaning.
2 Comments
execve() interface, but that doesn't mean the OP correctly translated their quoted-for-UNIX strings (if in fact they have any) to be correct Java literals.
-fis one argument,PostgreSQLis another; and any quotes which would be interpreted and removed by the shell (which is almost all of them) aren't supposed to be included in your execve array at all.-f Postgresql "PG:\"host='odisseu-db' user='postgres'\"", you would add-f,PostgresqlandPG:"host='odisseu-db' user='postgres'"as separate strings (no more backslashes except as Java syntax, and the outside quotes that are there for consumption by the shell being gone). That's in the UNIX world; if you're using Windows, things are different; the target platform should really be specified in the question to disambiguate.