Write HTML file using Java

前端 未结 10 907
我寻月下人不归
我寻月下人不归 2020-11-28 23:55

I want my Java application to write HTML code in a file. Right now, I am hard coding HTML tags using java.io.BufferedWriter class. For Example:

BufferedWrite         


        
10条回答
  •  一整个雨季
    2020-11-29 00:26

    Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.

    Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:

    String encoding = "UTF-8";
    FileOutputStream fos = new FileOutputStream("myfile.html");
    OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
    StreamResult streamResult = new StreamResult(writer);
    
    SAXTransformerFactory saxFactory =
        (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler tHandler = saxFactory.newTransformerHandler();
    tHandler.setResult(streamResult);
    
    Transformer transformer = tHandler.getTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "html");
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    
    writer.write("\n");
    writer.flush();
    tHandler.startDocument();
        tHandler.startElement("", "", "html", new AttributesImpl());
            tHandler.startElement("", "", "head", new AttributesImpl());
                tHandler.startElement("", "", "title", new AttributesImpl());
                    tHandler.characters("Hello".toCharArray(), 0, 5);
                tHandler.endElement("", "", "title");
            tHandler.endElement("", "", "head");
            tHandler.startElement("", "", "body", new AttributesImpl());
                tHandler.startElement("", "", "p", new AttributesImpl());
                    tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
                tHandler.endElement("", "", "p");
            tHandler.endElement("", "", "body");
        tHandler.endElement("", "", "html");
    tHandler.endDocument();
    writer.close();
    

    Note that XSLT transformer will release you from the burden of escaping special characters like >, as it takes necessary care of it by itself.

    And it is easy to wrap SAX methods like startElement() and characters() to something more convenient to one's taste...

提交回复
热议问题