简体   繁体   中英

New line character as part of the String

I've got the problem creating String looking as follows:

"SSR LANG SA  HK1/EN;S7;P1\n"+

Code that does that should append \\n as part of the string + quote + append string literal + actual new line literal:

javaFormattedText.append("   \""+ tokenizer.nextElement() + "\\n\"+\n");

The output String should look:

"SSR LANG SA  HK1/EN;S7;P1\n"+

But it looks:

"SSR LANG SA  HK1/EN;S7;P1
\n"+

Therefore java complains about unclosed string literal.

The purpose of doing it is generating test classes dynamically and those contain a lot of text information that needs to be java formatted strings.

How can achieve the target?

UPD

Solved the problem by doing this:

String line = (String) AIR_textTokenizer.nextElement();

line = line.replace("\n", "").replace("\r", "");

Your tokenizer.nextElement() is probably returning a trailing new line. To remove that:

String str = tokenizer.nextElement();
if (str.endsWith('\n')) {
    str = str.substring(0, str.length - 1);
}
javaFormattedText.append("   \""+ str +"\\n\"+\n");

如果您想添加行分隔符,请使用:System.lineSeparator();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM