views:

23

answers:

1
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);

String rowFormat = "%8s %8s %8s %8s%n";
pw.printf(rowFormat, "Col A", "Col B", "Col C", "Col XY");
pw.printf(rowFormat, "A", "19", "Car", "55");
pw.printf(rowFormat, "X", "21", "Train C", "-4");
pw.printf(rowFormat, "B", "-9", "Bike", "0");
String message = sw.toString();
System.out.println(message);

The above program prints the following table and the alignment is perfect.

Col A    Col B    Col C   Col XY   
    A       19      Car       55   
    X       21  Train C       -4   
    B       -9     Bike        0  

Instead of printing the string message, I am passing the string to another function which sends email with the content of the mail as the string message.

mail.setContent(message.toString(),"text/plain");

This is how I am setting the content as message in my mail.

But the alignment of the table is not appropriate as I do receive while printing the string. What must be done such that I receive the content of my mail as similar as the printing format of the string.

I can realize that setting the mime type as text/html and using the <table> tag for forming the table will help me to achieve the task required.

Kindly let me know, how and where should be the <table><tr><th> tags must be inserted inorder to find the tabular format in the content of the mail.

+2  A: 

Personally, I would use velocity for something like this, however, I think this is what you want:

String headerFormat = "<tr><th>%8s</th><th>%8s</th><th>%8s</th><th>%8s%n</th></tr>";
String rowFormat = "<tr><td>%8s</td><td>%8s</td><td>%8s</td><td>%8s%n</td></tr>";

pw.printf(headerFormat, "Col A", "Col B", "Col C", "Col XY");
pw.printf(rowFormat, "A", "19", "Car", "55");
pw.printf(rowFormat, "X", "21", "Train C", "-4");
pw.printf(rowFormat, "B", "-9", "Bike", "0");

String message = "<table>" + sw.toString() + "</table>";
System.out.println(message);

You can get more info on html tables here.

javamonkey79
You can probably get rid of the '%8' and '%n' values and instead use just '%s' - but it doesn't matter as most (if not all) html renderers will ignore the extra whitespace anyways.
javamonkey79
@javamonkey79 Thanks a lot!!!
LGAP
@LGAP: Quite welcome.
javamonkey79