Simple/Direct/Heredoc way of constructing a HTML string in Java
Asked Answered
P

6

24

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?

Papeterie answered 20/4, 2010 at 20:43 Comment(3)
For future reference, those sorts of things are usually called heredocsIgraine
This answer shows how to paste multi-line escaped strings in Eclispe.Dung
For the quotes: #3034686 , for the multiline: https://mcmap.net/q/63965/-does-java-have-support-for-multiline-stringsHyperpituitarism
T
22

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.

Tommietommy answered 20/4, 2010 at 21:0 Comment(1)
There is always a checkbox somewhere ;o)Papeterie
P
2

To echo benjismith's trick from a similar question, you can use an alternate character and replace them afterwards:

String myString = "using `backticks` instead of quotes".replace('`', '"');

I found it helpful when I was writing tests with JSON

String json = "{`kind`:`file`,`sid`:802,`rid`:5678 ,`attrs`:{`name`:`FILE-WG-2468`}}".replace('`', '"');
// vs
String json = "{\"kind\":\"file\",\"sid\":802,\"rid\":5678 ,\"attrs\":{\"name\":\"FILE-WG-2468\"}}";
Pumpkinseed answered 21/10, 2016 at 16:51 Comment(1)
lacking heredocs is presently the item I most detest on java but this is a nice hack to reduce the pain. I will compose the correct string then use Intellij "replace within selection" to say ~ (used less frequently than '`')Amazonas
K
1

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

Kinny answered 20/4, 2010 at 20:46 Comment(2)
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.Papeterie
Window>Preferences>Java>Editor>Typing check Escape text when pastin a string literalKinny
B
1

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

Bitthia answered 20/4, 2010 at 20:59 Comment(0)
D
1

Text blocks

Text Blocks feature arrived in Java 15. For details, see JEP 378: Text Blocks.

Enclose your material in a pair of triple QUOTATION MARK characters.

String html = """
              <html>
                  <body>
                      <p>Hello, world</p>
                  </body>
              </html>
              """;

Your IDE has likely been updated to be savvy in assisting you with editing text blocks. For example, IntelliJ offers support.

Dialogist answered 12/3, 2022 at 4:58 Comment(0)
P
0

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.

Pedi answered 20/4, 2010 at 20:48 Comment(3)
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)Papeterie
Agree - all depends on context. Sounds like the Eclipse trick is ftw in this case!Pedi
Embedded heredoc's are a core part of my development process especially in testcases and configuration related logic. I was (fortunately) away from java for 6 years but coming back is v painful with this front and center. The trick above about replacing double quotes with something else is probably the least painful hack at this point.Amazonas

© 2022 - 2025 — McMap. All rights reserved.