Java String vs. Command Line Argument

时光怂恿深爱的人放手 提交于 2019-12-25 06:26:42

问题


Why does it happen that a command line argument passed to a Java class seems to be automagically escaped while in an instantiated String object the escape character () is seemingly ignored.

For example, if start with a string like this:

SELECT * FROM my_table WHERE my_col like 'ABC_\' ESCAPE '\'

And I try running it through a simple class like this:

public class EscapeTest {
    public static void main (String[] args) {
        String str = "SELECT * FROM my_table WHERE " 
                     + "my_col like 'ABC_\' ESCAPE '\'";
        System.out.println("ARGS[0]: "+args[0]);
        System.out.println("STR: "+str);
}
}

and I pass the "SELECT" statement above in as a command line arg, I get output that looks like this:

ARGS[0]: SELECT * FROM my_table WHERE my_col like 'ABC_\' ESCAPE '\'

STR: SELECT * FROM my_table WHERE my_col like 'ABC_' ESCAPE ''

If I look at the value of ARGS[0] in the Eclipse debugger I see that the slashes are escaped. Why does this happen? Makes it kind of hard to predict I think.


回答1:


The contents of your string str does not contain any backslashes. Those are being handled by the Java compiler understanding the escape sequences of Java string literals.

The command line processor presumably isn't doing that - it's not treating backslash specially in any way, although this will depend on your shell. (In most Unix shells it would treat backslash differently. My guess is that you're on Windows.)

So, your command line argument does have backslashes in. They haven't been escaped by the executing Java process - they're just "there" in the string.

Now it sounds like the debugger is escaping the string when it's displaying it to you, so that you can see things like tabs and newlines. It's important to understand that this is just the way the debugger displays the string - there's no such thing as an "escape" within a Java string itself.

EDIT: As per comment:

To express this string in Java source code, you have to escape the backslashes:

String str = "SELECT * FROM my_table WHERE my_col like 'ABC_\\' ESCAPE '\\'"; 

Backslashes have to be escaped as backslash is the escape character in Java string literals.



来源:https://stackoverflow.com/questions/6794908/java-string-vs-command-line-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!