我编写了一段Java代码,该代码在html表中显示了结果。相同的代码多次调用不同的值,我需要显示html表中的所有值。当前使用我的代码它是覆盖并仅显示html中的最后一个方法调用值。
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class TableTest {
void meth1(String c1,String c2,String c3){
//business logic
tableCreation(String c1,String c2,String c3);
}
void meth2(String c1,String c2,String c3){
//business logic
tableCreation(String c1,String c2,String c3);
}
void meth3(String c1,String c2,String c3){
//business logic
tableCreation(String c1,String c2,String c3);
}
void tableCreation(String c1, String c2, String c3) throws IOException {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("results.html"));
writer.write("<html>" + "<body>" + "<table border ='1'>" + "<tr>" + "<th>Col1</th>" + "<th>Col2</th>"
+ "<th>Col3</th>" + "</tr><tr>");
/*
* for (int i=1;i<=3;i++) { writer.write("<td>"); //some business logic here
* writer.write("-aaaaa-"); writer.write("</td> "); }
*/
writer.write("<td>");
writer.write(c1);
writer.write("</td> ");
writer.write("<td>");
writer.write(c2);
writer.write("</td> ");
writer.write("<td>");
writer.write(c3);
writer.write("</td> ");
writer.write("</tr></table>" + "</body>" + "</html>");
writer.close();
} catch (IOException e) {
System.out.println("IO EXCEPTION-----" + e);
}
System.out.println("----------END---------------");
}
public static void main(String[] args) throws IOException {
// the below method calls are dynamic, don't know how many times
// tableCreation(..) is being called
new TableTest().meth1("R1Tst1", "R1Tst2", "R1Tst3");
new TableTest().meth2("R2Tst1", "R2Tst2", "R2Tst3");
new TableTest().meth3("R3Tst1", "R3Tst2", "R3Tst3");
}
}
结果:
Col1 Col2 Col3
R3Tst1 R3Tst2 R3Tst3
预期结果:
Col1 Col2 Col3
R1Tst1 R1Tst2 R1Tst3
R2Tst1 R2Tst2 R2Tst3
R3Tst1 R3Tst2 R3Tst3
答案 0 :(得分:2)
您可以借鉴构建器模式。
下面我要做的是创建HtmlTableBuilder
类的实例,在其中添加了html文件的第一部分。之后,您可以使用add()
方法添加行,并使用build()
方法完成操作,该方法还将添加html文件的结尾部分并返回HtmlTable
的实例。这样,您可以写到您的BufferedWriter
。
public class HtmlTable {
String html;
public HtmlTable(String html) {
this.html = html;
}
public static class HtmlTableBuilder {
String html;
public HtmlTableBuilder() {
html = "<html>" +
"<body>" +
"<table border ='1'>" +
"<tr>" +
"<th>Col1</th>" +
"<th>Col2</th>" +
"<th>Col3</th>" +
"</tr>";
}
public HtmlTableBuilder addRow(String col1, String col2, String col3) {
html += "<tr>" +
"<td>" +
col1 +
"</td><td>" +
col2 +
"</td><td>" +
col3 +
"</td>" +
"</tr>";
return this;
}
public HtmlTable build() {
html += "</table>" +
"</body>" +
"</html>";
HtmlTable toReturn = new HtmlTable(html);
return toReturn;
}
}
public static void main(String[] args) {
HtmlTable table = new HtmlTableBuilder()
.addRow("R1Tst1", "R1Tst2", "R1Tst3")
.addRow("R2Tst1", "R2Tst2", "R2Tst3")
.addRow("R3Tst1", "R3Tst2", "R3Tst3")
.build();
BufferedWriter writer = new BufferedWriter(new FileWriter("results.html"));
writer.write(table);
writer.close();
}
}
这是一个包含三列的表。当然,您可以利用自己的想象力,将其转换为具有非预定义列数的更通用的解决方案。在这种情况下,您将例如使用Strings
方法中的add()
列表。