Navaneeth K N
Navaneeth K N

Reputation: 15501

Escaping filenames when passing as an argument

My Java program is launching another process and passing a file's absolute path as command line argument. The path may contain spaces. So I am quoting the path before adding it to the arguments. When a double quote appears in the path, I am escaping it with \.

Here is the code:

private String escapeQuotes(String original) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < original.length(); i++) {
        if (original.charAt(i) == '"') {
            builder.append('\\');
        }
        builder.append(original.charAt(i));
    }
    return builder.toString();
}

I use it like,

String args = " \"" + escapeQuotes(filePath) + "\"";

This works well. But I am wondering is this approach fool proof? Or is there anything else that I should handle like the way I have escaped double quotes?

Any help would be great!

Upvotes: 0

Views: 588

Answers (3)

jlordo
jlordo

Reputation: 37813

As per my comment under the post: IMHO, the method is not fool proof because it would also escape quotes that are already escaped. I would use:

private String escapeQuotes(String original) {
    return original.replaceAll("(?<!\\\\)\"", "\\\\\"");
}

Then

System.out.println(escapeQuotes("Not escaped\", escaped\\\""));

prints

Not escaped\", escaped\"

in the console, whereas your version would print

Not escaped\", escaped\\"

Upvotes: 1

mikej
mikej

Reputation: 66263

How are you launching the other process? If you are using the version of Runtime.exec that takes an array then there is no need to escape spaces in any of the arguments.

e.g.

Runtime.getRuntime().exec(new String[] { "notepad.exe", 
    "c:\path with spaces\afile.txt" });

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

I don't think you need to do this, eg

Runtime.getRuntime().exec(new String[] {"cmd", "/c", "dir", "d:/test ;test"})

works fine, note that "f:/test ;test" contains bot ' ' and ';'

Upvotes: 1

Related Questions