tags:

views:

37

answers:

3

Given a dictionary:

1=f00
2=bar
3=larodi
.
.
.

and some html files like:

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>  
   content content content {1} bla
   bla bla {3} &%$*#$*$%# {2} and so on...
</body>
</html>

How to replace the keys in the files with their values with java? I've read about java.text.MessageFormat, but cannot come up with a way to use it.

+1  A: 
String result = MessageFormat.format(htmlString, "foo", "bar", "larodi");


String[] paramas = {"foo" , ....};
String result = MessageFormat.format(htmlString, params);

htmlString is your html content.

mohammad shamsi
ok, but if I have more than 100 numbers to replace, can I write all of them as parameters in this function?
brain_damage
@brain_damage: you can send them as array of Objects or String to function.
mohammad shamsi
thank you both : )
brain_damage
+1  A: 

You may want to check some java template engines like freemarker and velocity.

Daniel Moura
thanks, I'll check them :)
brain_damage
+1 - or even JSP / JSTL. `MessageFormat` is very limited in what it can do.
Stephen C
A: 

It seems to me that a message formatter does not use dictionaries, but arrays. Your '1' is, as such, not a key but an index.

It looks a bit like you remember the python % operator. This isn't like that. MessageFormat uses a positional system. Either by entering the parameters directly, or by giving an array.

extraneon
I've not decided how to represent my data yet. But yes, I'm still thinking in Python and it;s hard to start changing my view and think in Java :D
brain_damage
@brain_damage the python standard library is a bit more high-level than the java one. In java it is much more common to use external dependencies to make common jobs fairly easy. That's why tools like maven are so popular. In your case a templating dependency like velocity might be more natural than hacking something on your own. Python on the other hand has al those convenience things built-in, and if you easy-install something it's usually something large and comolex, like sqlalchemy or twisted.
extraneon