How to use Java to edit a template document (letter form) from a file?

I am playing Java for the first time and should be able to replace some words in the template. example template -

"Dear PUT_THEIR_NAME_HERE,

I appeal to you ..... bla bla bla

Hi,

PUT_COMPANY_NAME_HERE "

What is the easiest way (preferably using the standard library) to make a copy of this template file and add the correct words to the right place, and then save it to the file system? I have to make many such simple templates, so a way that can be easily replicated will be nice.

I also access Java via JavaScript using Rhino, not sure if it matters or not.

Hi,

Chris

+3
source share
7 answers

You are looking for java.text.MessageFormat:

Here are some usage examples (from JavaDoc):

Object[] arguments = { new Integer(7), new Date(System.currentTimeMillis()), "a disturbance in the Force" }; String result = MessageFormat.format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", arguments); output: At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7. 
+12
source

For advanced functions (e.g. loops) you can use Apache or FreeMarker speed .

+5
source

Really simplified:

Of course, not bulletproof.

 C:\oreyes\samples\java\replace>type Simplistic.java public class Simplistic{ public static void main( String [] args ) { String template = "Dear _NAME_HERE_. I'm glad you..."; System.out.println( template.replaceAll("_NAME_HERE_","Oscar Reyes")); } } C:\oreyes\samples\java\replace>java Simplistic Dear Oscar Reyes. I'm glad you... 

Here is a formal document for this method, if you want to continue the study

http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)

I am glad to hear that you are learning java!

+2
source

The current highly rated position is an accurate, but not the most difficult way to use the API in Java 6. There is no need to create an array of arguments or explicitly enter an integer, and the new Date () uses the current default time:

String result = MessageFormat.format ("At {1, time} at {1, date}) {2} on the planet {0, number, integer}.", 7, new Date (), "a violation is valid") ;

A few tips to make your code more readable and easier to maintain.

+1
source

I wrote a class for this when I ported the application to java ~ 10 years ago:

http://github.com/dustin/spyjar/tree/master/src/java/net/spy/util/SpyToker.java

0
source

You can use StringSubstitutor library class commons-lang

0
source

Well, the easiest way is to read the file in a line, do replaceAll (once for every word you want to replace), and then write the result to a new file. This is not the most efficient approach, but it works well enough for simple tasks.

-one
source

All Articles