Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Tiny Avatar asked Jul 10 '13 11:07

Tiny


People also ask

How do you format something in Java?

The most common way of formatting a string in java is using String. format(). If there were a “java sprintf” then this would be it.

What is ICU format?

The ICU format is a widely used message format in numerous translation software systems and i18n libraries. It provides a clear view of the expected data in the source messages. If you have ever localized a software project, you have most likely used the ICU message format.


1 Answers

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\re will be produced rather than Youre. (before double quote solution '' applied)

like image 171
Reimeus Avatar answered Sep 28 '22 19:09

Reimeus