加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java代码创建html文件并动态添加行

发布时间:2020-12-15 02:12:50 所属栏目:Java 来源:网络整理
导读:我想用 java创建log.html文件,其中我会在错误被捕获时将错误转储到html表行. 我创建了表列,但是当我向它传递任何内容时,我的数据将覆盖列名而不是追加行. 我的java代码如下: public static void main(String[] args) throws IOException{ String month = ge
我想用 java创建log.html文件,其中我会在错误被捕获时将错误转储到html表行.
我创建了表列,但是当我向它传递任何内容时,我的数据将覆盖列名而不是追加行.
我的java代码如下:

public static void main(String[] args) throws IOException
{
    String month = getMonth(1);
    System.out.println(month);
    //table(month);
    addrow("abc");
}
public static void table(String Update) throws IOException
{
    //define a HTML String Builder
    StringBuilder htmlStringBuilder=new StringBuilder();
    htmlStringBuilder.append("<html><head><title>Packaging Issues</title></head>");
    htmlStringBuilder.append("<body><h1> Files Received </h1>");
    htmlStringBuilder.append("<table border="1" bordercolor="#000000">");
    htmlStringBuilder.append("<tr><td><b>Cycle</b></td><td>"+Update+"</td></tr>");
    htmlStringBuilder.append("<tr><td><b>Version</b></td><td></tr>");
    newtable(htmlStringBuilder.toString());
}
public static void newtable(String a)
{
    StringBuilder htmlStringBuilder=new StringBuilder();
    htmlStringBuilder.append(a);
    htmlStringBuilder.append("<h1> Issues Found </h1>");
    htmlStringBuilder.append("<table border="1" bordercolor="#000000">");
    htmlStringBuilder.append("<tr><td><b>Type</b></td>");
    htmlStringBuilder.append("<td><b>Field</b></td>");
    htmlStringBuilder.append("<td><b>Issue</b></td></tr>");
    addrow(htmlStringBuilder.toString());
     // WriteToFile(htmlStringBuilder.toString(),"log.html");
}

public static void addrow(String a)
{
    try {
        StringBuilder htmlStringBuilder=new StringBuilder();
        htmlStringBuilder.append("<tr><td><b>"+a+"</b></td>");
        htmlStringBuilder.append("<td><b>Field</b></td>");
        htmlStringBuilder.append("<td><b>Issue</b></td></tr>");
        htmlStringBuilder.append("</table></body></html>");
        WriteToFile(htmlStringBuilder.toString(),"log.html");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是writetofile方法:

public static void WriteToFile(String fileContent,String fileName) throws IOException {
    String projectPath = "/home/abc";
    String tempFile = projectPath + File.separator+fileName;
    File file = new File(tempFile);
    // if file does exists,then delete and create a new file
          //write to file with OutputStreamWriter
    OutputStream outputStream = new FileOutputStream(file.getAbsoluteFile());
    Writer writer=new OutputStreamWriter(outputStream);
    writer.write(fileContent);
    writer.close();

}

如果还有其他办法,请分享.谢谢你的支持

解决方法

构造函数FileOutputStream(file)会覆盖文件的内容.请改用 this constructor

FileOutputStream fos =new FileOutputStream(file,true) ;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读