Neeraj
Neeraj

Reputation: 1680

Storing html file in a String in java

I am sending emails using amazon java sdk. I have to send html template as mail. I have written a program for this and it is working fine. But now I am storing the whole html code in a single String. But whenever i need to edit the template, I have to edit the program (I mean the String variable). And also I have to take care the special characters like " \ ...etc in that html code. Please suggest me an elegant way to solve this issue.

Upvotes: 0

Views: 5385

Answers (4)

Neeraj
Neeraj

Reputation: 1680

Better and easiest way is reading the html file line by line using simple file reading operation and append this each line to a single String. And also I found this solution (also a better one, if you are ready to add one more library file to your project) from SO.

Upvotes: 0

mtk
mtk

Reputation: 13709

Check the Apache Velocity Project. You can create template for several things. From it's user-guide page

Velocity can be used to generate web pages, SQL, PostScript and other output from templates. It can be used either as a standalone utility for generating source code and reports, or as an integrated component of other systems.

You can use a VTL(Velocity Template Language) . A example from above link

<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $mud in $mudsOnSpecial )
   #if ( $customer.hasPurchased($mud) )
      <tr>
        <td>
          $flogger.getPromo( $mud )
        </td>
      </tr>
   #end
#end
</table>

Upvotes: 1

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Use Apache Common Lang api's StringEscapeUtils#escapeHtml, It escapes the characters in a String using HTML entities and return a new escaped String, null if null string input.

For example:

"US" & "UK"

becomes:

&quot;US&quot; &amp; &quot;UK&quot;.

Upvotes: 1

Andrey Adamovich
Andrey Adamovich

Reputation: 20663

Use a template engine for that and store your template externally either in class path or on a file system. Here is a question that may help you selecting one: https://stackoverflow.com/questions/2381619/best-template-engine-in-java

Upvotes: 2

Related Questions