命令行参数中的转义序列 (Java)
Escape sequences in command line arguments (Java)
根据How to use line break argument
When you define a String as "Hello\nHello" in Java, it contains no '\'
character. It is an escape sequence for the line break: "\n" is just
one character.
When you use this string as an argument to your
program, however (so the string is defined outside), "\n" is
interpreted as two characters: '\' and 'n'.
为什么不编译包含转义序列的命令行参数?我认为命令行参数被放入数组 String[] args?
而 String[] args 将包含 args[0] = "Hello\nJava";
Command-line 参数不是 Java 源代码,因此 Java 源代码中的字符含义规则不适用。
command-line 参数的解释或其他方式是命令解释器的职责; Java没有特殊对待。例如,在大多数(所有?)Linux shells:
中,\n 不会在 quoted-string 中被替换
$ echo 'a \n b'
a \n b
在引号之外,backslash-n 表示 'literally n',这与 'n' 相同,因为 'n' 与 [=34= 没有任何特殊之处].
$ echo a\nb
anb
当然,Java 系统可以在命令解释器之后应用自己的处理,但是大多数 Linux 用户会觉得这很混乱; Java 与其他命令相比,命令的行为会不一致。
转义序列不会被命令 shell 转换成相应的字符代码 (How can I echo a newline in a batch file?),所以您想知道的是为什么 java
程序不对接收到的参数进行一些处理调用它时。好吧,原因很简单:按摩是任意,也许有些用户不希望将字符串解释为人类文本;但是表示其他事物的字符串,其中转义代码的任意转换是失败的概括。一些例子:
- 字符串是 windows 文件路径,如
c:\my\folder\number\n
,在那里你可以找到两个 \n
如果 java 会被任意概括为人类文本将成为一个主要错误。
- 文字
ids
、密码、ascii 艺术、
- 可序列化内容的结构化表示,例如 xml、模型对象、专有内容等
现在,如果你定义要编译的字符串INSIDE java代码,编译后所有\?
都会被编译成它们对应的转义码(作为语言的一个特征);但是你可以通过转义来告诉 java 编译器不要这样做,即 \?
;但是这个编译问题。在运行时,所有字符串都不过是 char[]
并且没有对它们应用任意按摩。
It is a compile-time error if the character following a backslash in an escape is not an ASCII b, t, n, f, r, ", ', \, 0, 1, 2, 3, 4, 5, 6, or 7. The Unicode escape \u is processed earlier (§3.3).
根据How to use line break argument
When you define a String as "Hello\nHello" in Java, it contains no '\' character. It is an escape sequence for the line break: "\n" is just one character.
When you use this string as an argument to your program, however (so the string is defined outside), "\n" is interpreted as two characters: '\' and 'n'.
为什么不编译包含转义序列的命令行参数?我认为命令行参数被放入数组 String[] args?
而 String[] args 将包含 args[0] = "Hello\nJava";
Command-line 参数不是 Java 源代码,因此 Java 源代码中的字符含义规则不适用。
command-line 参数的解释或其他方式是命令解释器的职责; Java没有特殊对待。例如,在大多数(所有?)Linux shells:
中,\n 不会在 quoted-string 中被替换 $ echo 'a \n b'
a \n b
在引号之外,backslash-n 表示 'literally n',这与 'n' 相同,因为 'n' 与 [=34= 没有任何特殊之处].
$ echo a\nb
anb
当然,Java 系统可以在命令解释器之后应用自己的处理,但是大多数 Linux 用户会觉得这很混乱; Java 与其他命令相比,命令的行为会不一致。
转义序列不会被命令 shell 转换成相应的字符代码 (How can I echo a newline in a batch file?),所以您想知道的是为什么 java
程序不对接收到的参数进行一些处理调用它时。好吧,原因很简单:按摩是任意,也许有些用户不希望将字符串解释为人类文本;但是表示其他事物的字符串,其中转义代码的任意转换是失败的概括。一些例子:
- 字符串是 windows 文件路径,如
c:\my\folder\number\n
,在那里你可以找到两个\n
如果 java 会被任意概括为人类文本将成为一个主要错误。 - 文字
ids
、密码、ascii 艺术、 - 可序列化内容的结构化表示,例如 xml、模型对象、专有内容等
现在,如果你定义要编译的字符串INSIDE java代码,编译后所有\?
都会被编译成它们对应的转义码(作为语言的一个特征);但是你可以通过转义来告诉 java 编译器不要这样做,即 \?
;但是这个编译问题。在运行时,所有字符串都不过是 char[]
并且没有对它们应用任意按摩。
It is a compile-time error if the character following a backslash in an escape is not an ASCII b, t, n, f, r, ", ', \, 0, 1, 2, 3, 4, 5, 6, or 7. The Unicode escape \u is processed earlier (§3.3).