Java equivalent of C#'s verbatim strings with @
C#JavaStringLiteralsC# Problem Overview
Quick question. Is there an equivalent of @ as applied to strings in Java:
For example I can do @"c:\afolder\afile"
in C# and have it ignore the escape characters when processing instead of having to do "c:\\afolder\\aFile"
. Is there a Java equivalent?
hmmm: stackoverflow is escaping on me .. lol. The second example should read:
c:(double-backslash)afolder(double-backslash)aFile
C# Solutions
Solution 1 - C#
No. Escaping / externalizing the string is your only choice.
Solution 2 - C#
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.
Solution 3 - C#
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".
Solution 4 - C#
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 ``.
Solution 5 - C#
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