views:

295

answers:

4

In python I can construct a HTML string without worrying about escaping special characters like < or " by simply enclosing the string in triple quotes like:

html_string = """
<html>
<body>
<p>My text with "quotes" and whatnot!<p>
</body>
</html>
"""

Is there a similar way to do this in Java?

+1  A: 

No, but some tools escape it for you when you paste it, like eclipse.

Lucass
Nice, didn't know that! How would you do it in Eclipse? I'm running Eclipse Galileo and when I paste HTML code it is just being copied.
das_weezul
Window>Preferences>Java>Editor>Typing check Escape text when pastin a string literal
Lucass
A: 

In Java source code, double quote is a special character, used to declare string literals. You cannot have a double quote in a String literal without escaping it.

In general, I would try to avoid hard-coding strings like that in source code, particularly if I found myself doing it a lot - as you've noted, they're a pain to deal with as source and they might be quite likely to change, in which case you could do without recompiling. If you don't need to supply runtime parts to the text data, you could get away with something as simple as reading in the data from a properties file, or you could use a templating engine like Apache Velocity to keep the character data separate and still substitute variables at runtime - several of the examples in the linked user guide do exactly that with HTML.

Brabster
I totally agree, but for a quick test (to pin down a bug) I always like to have some quick-n-dirty tricks up my sleeve ;o)
das_weezul
Agree - all depends on context. Sounds like the Eclipse trick is ftw in this case!
Brabster
+1  A: 

For the purpose mentioned, Java Server Pages do the trick even without the tripple """'s :-)

rsp
+4  A: 

It can't be done in Java like in Python. However if you are using Eclipse go to Window->Preferences->Java->Editor->Typing The last check box is "Escape text when pasting into a String literal". Check that. Now when you paste when your cursor is between quotation marks it'll be escaped.

Adam
There is always a checkbox somewhere ;o)
das_weezul