C # 的逐字字符串与@的 Java 等效

快速问答: 在 Java 中,字符串是否等价于@:

例如,我可以在 C # 中执行 @"c:\afolder\afile",并让它在处理时忽略转义字符,而不必执行 "c:\\afolder\\aFile"。有 Java 等价物吗?

第二个例子应该是:

(双反斜杠)文件夹(双反斜杠) aFile

30974 次浏览

No. Escaping / externalizing the string is your only choice.

No, Java doesn't have verbatim string literals.

If you want a Java-like (and Java-VM-based) language that does, however, you might want to look at Groovy which has various forms of string literal.

As Kent and Jon have said, no there isn't.

I'm answering just to point out that even if there were, for your particular case, it would be a bad idea in the general case, assuming a more than one-off program.

Java programs run on more platforms than just Windows, and other platforms have different file delimiters. So instead of dealing with escaped backslashes, the correct way to handle your particular example is by getting the file separator property:


String sep = System.getProperty("file.separator");
String filename = ROOTDIR + sep + "folder" + sep + "afile";

Where you'd have separately created ROOTDIR based on some policy - not only the platform, but whether you want your "afile" to be relative to the actual file system root, or relative to the user's home directory.

But definitely, using the file separator property makes your programs more widely usable. Is it more work? Yes. As Wanda Sykes says, "But it's worth it".

Currently it is not supported in Java but could be available in future releases. There was created JEP 326: Raw String Literals at 2018/01/23

See the progress at https://bugs.openjdk.java.net/browse/JDK-8196004

Probably some day you will be able to do it with:

`c:\afolder\afile`

UPDATE: JEP proposed to drop from JDK 12:326: Raw String Literals (Preview) You can read the rationale here: http://mail.openjdk.java.net/pipermail/jdk-dev/2018-December/002402.html

And more details here https://bugs.openjdk.java.net/browse/JDK-8215682

The bottom line: There will not be verbatim strings in Java in near future. And even if it will appear it rather will not be ``.

Java has it since September 2019, but it used different sintax. “”” (three double-quote marks).

*In more recent java versions (+13 in preview, +15 as production ready), mostly equivalent can be achieved with java text blocks.

String html = """
<xml>
<ody>
<pan>example xml </pan>
</ody>
</xml>""";

Documentation on https://docs.oracle.com/en/java/javase/13/text_blocks/index.html