Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

resourcebundle - Format a message using MessageFormat.format() in Java

I have stored some messages in a resource bundle. I'm trying to format these messages as follows.

import java.text.MessageFormat;

String text = MessageFormat.format("You're about to delete {0} rows.", 5);
System.out.println(text);

Assume that the first parameter i.e the actual message is stored in a property file which is somehow retrieved.

The second parameter i.e 5 is a dynamic value and should be placed in the placeholder {0} which doesn't happen. The next line prints,

Youre about to delete {0} rows.

The placeholder is not replaced with the actual parameter.


It is the apostrophe here - You're. I have tried to escape it as usual like You\'re though it didn't work. What changes are needed to make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add an extra apostrophe ' to the MessageFormat pattern String to ensure the ' character is displayed

String text = 
     java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
                                         ^

An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc

A single quote itself must be represented by doubled single quotes '' throughout a String.

The String You\'re is equivalent to adding a backslash character to the String so the only difference will be that You e will be produced rather than Youre. (before double quote solution '' applied)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...