• Post Reply Bookmark Topic Watch Topic
  • New Topic

Replace tokens in a file  RSS feed

 
Mary Cole
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a huge file which has some tokens which has toe be populated dynamicallly based on certain data from DB. The tokens are in format . I need to get these values from DB and replace teh same in the files....How can I do it ? any thoughts?
 
Brian Cole
Author
Ranch Hand
Posts: 949
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Mary Cole:
I have a huge file which has some tokens which has toe be populated dynamicallly based on certain data from DB. The tokens are in format . I need to get these values from DB and replace teh same in the files....How can I do it ? any thoughts?


There's no real way to do this "in place" (if that's what you are getting at) unless everything that might replace $NAME was exactly of length 5, etc. You essentially have to copy the file, even if it is huge.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would probably create a Map containing all the keys to be replaced ("NAME", "COUNTRY", etc) and all the values that they should be replaced with, loaded from the database. Then create a regular expression to look for a word to replace:

You might want the pattern to grab both the word and the text that preceded it:

Then you can use a Scanner to open the file and look for the next occurrance of the pattern. Write a loop to do this repeatedly. Every time you find a new $WORD to replace, write the preceding text to an output file, then look up the word in your map, and write the replacement text to the output file. At the end of the loop, be sure to write all remaining text (that came after the last matched $WORD). Does that help? I don' t know how familiar you are with regular expressions or scanners, so I just gave a quick high-level summary.

Note that you can also use an existing template engine like Velocity or Freemarker. Here is a nice article about these. The syntax they use may be a little different, but they're probably faster and more efficient than what most programmers will come up with by themselves (without a lot of work on optimizing).
 
Mary Cole
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply...but it was a quick and good reply but if you could provide me a sample skeletal code that would be great as this stuff is pretty new to me
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a quick version. It's not necessarily the fastest way to do this, but it should work:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!