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

泄露秘密 提交于 2019-11-28 23:04:39

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.

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

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

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.

jcadcell

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\"}}";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!