views:

236

answers:

3

Hi all,

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

+2  A: 

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

HTH,
Kent

Kent Boogaart
wow that's the fastest answer I've ever received here. Had to check over my shoulder .. lol .. spooky .. many Thanks Kent
Simon Rigby
+5  A: 

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.

Jon Skeet
A rock star moment. A response from the THE Jon Skeet :). Many Thanks
Simon Rigby
+1  A: 

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

CPerkins
Hiya and thanks. the fact that its a 'filename' in my case in kind of irrelevant. All my code is doing is taking a string (or trying to) and passing it on. I don't actually do anything with it other than pass it on to a web service. I was testing the response from a c# WCF service being called from Java. As I was just hard coding a test it was at this point that I discovered this limitation. I;m not actually doing anything 'file based' with the string.
Simon Rigby