Java字符串与命令行参数 [英] Java String vs. Command Line Argument

查看:167
本文介绍了Java字符串与命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会发生这样的情况:传递给Java类的命令行参数似乎被自动转义了,而在实例化的String对象中,转义符()似乎被忽略了。

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);
}
}

我将上面的 SELECT语句传递为命令行arg,我得到的输出看起来像这样:

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 ''

如果我在Eclipse调试器中查看ARGS [0]的值,我会看到斜杠被转义了。为什么会这样?我觉得很难预测。

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.

推荐答案

字符串 str 的内容不包含任何反斜杠。这些正在由Java编译器处理,了解Java字符串文字的转义序列。

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.

命令行处理器大概不是 这样做-它不会以任何方式专门处理反斜杠,尽管这取决于您的shell。 (在大多数Unix shell中,使用不同的反斜杠。我猜您在Windows上。)

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.)

因此,您的命令行参数 中包含反斜杠。它们没有被正在执行的Java进程转义-它们只是字符串中的那里。

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.

现在,听起来像 debugger 在向您显示字符串时正在转义该字符串,以便您可以看到制表符和换行符。重要的是要了解这只是调试器显示字符串的方式-在Java字符串本身中没有转义之类的东西。

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.

编辑:根据评论:

要在Java源代码中表示此字符串,您必须转义反斜杠:

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 '\\'"; 

反斜杠必须转义,因为反斜杠是Java字符串文字中的转义字符。

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

这篇关于Java字符串与命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆