- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Write HTML file using Java
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:
Is there any easier way to do this, as I have to create tables and it is becoming very inconvenient?
11 Answers 11
If you want to do that yourself, without using any external library, a clean way would be to create a template.html file with all the static content, like for example:
Put a tag like $tag for any dynamic content and then do something like this:
Note: I used org.apache.commons.io.FileUtils for simplicity.

- 4 For Java8, pass extra Charset.forName("UTF-8") because readFileToString without charset is deprecated. – Jitesh Sojitra Oct 9, 2016 at 17:03
- 2 It is also possible to use MessageFormat for substitutions: String template = FileUtils.readFileToString(htmlTemplateFile); String title = "New Page"; String body = "This is Body"; String htmlString = MessageFormat.format(template, title, body); And template should then contain {0} for title and {1} for body . – Sergey Ushakov Mar 17, 2017 at 1:50
A few months ago I had the same problem and every library I found provides too much functionality and complexity for my final goal. So I end up developing my own library - HtmlFlow - that provides a very simple and intuitive API that allows me to write HTML in a fluent style. Check it here: https://github.com/fmcarvalho/HtmlFlow (it also supports dynamic binding to HTML elements)
Here is an example of binding the properties of a Task object into HTML elements. Consider a Task Java class with three properties: Title , Description and a Priority and then we can produce an HTML document for a Task object in the following way:

- 1 A nice idea, and a nice tool, but unfortunately the license is not as nice so to encourage really broad use... ;) – Sergey Ushakov Mar 17, 2017 at 2:02
- @s-n-ushakov Sorry, I am not an expert about license agreements. What's the problem with GPL v3.0? – Miguel Gamboa Mar 17, 2017 at 10:39
- 5 The problem with GPL is that it is too restrictive. It requires you to disclose all your project under GPL too, if you use just any piece of GPL-licensed code. This may be no problem for hobby or university programming, but it may be quite a problem for business-related programming. So to make your library more business-friendly, I might suggest to change the license at least to LGPL, which does not require you to opensource all your project, but only requires to disclose your improvements to the library. Other licenses, maybe slightly more business friendly, are BSD, MIT, Apache, Eclipse... – Sergey Ushakov Mar 18, 2017 at 5:17
- 1 @s-n-ushakov I will change the license to MIT. Thanks for your advice. – Miguel Gamboa Mar 21, 2017 at 9:20
- 7 @s-n-ushakov DONE. Just release it version 1.1. with MIT license and a couple of minor fixes. – Miguel Gamboa Mar 23, 2017 at 16:46
You can use jsoup or wffweb (HTML5) based.
Sample code for jsoup:-
Sample code for wffweb:-
prints (in minified format):-
Velocity is a good candidate for writing this kind of stuff. It allows you to keep your html and data-generation code as separated as possible.

I would highly recommend you use a very simple templating language such as Freemarker
It really depends on the type of HTML file you're creating.
For such tasks, I use to create an object, serialize it to XML, then transform it with XSL. The pros of this approach are:
- The strict separation between source code and HTML template,
- The possibility to edit HTML without having to recompile the application,
- The ability to serve different HTML in different cases based on the same XML, or even serve XML directly when needed (for a further deserialization for example),
- The shorter amount of code to write.
The cons are:
- You must know XSLT and know how to implement it in Java.
- You must write XSLT (and it's torture for many developers).
- When transforming XML to HTML with XSLT, some parts may be tricky. Few examples: <textarea/> tags (which make the page unusable), XML declaration (which can cause problems with IE), whitespace (with <pre></pre> tags etc.), HTML entities ( ), etc.
- The performance will be reduced, since serialization to XML wastes lots of CPU resources and XSL transformation is very costly too.
Now, if your HTML is very short or very repetitive or if the HTML has a volatile structure which changes dynamically, this approach must not be taken in account. On the other hand, if you serve HTML files which have all a similar structure and you want to reduce the amount of Java code and use templates, this approach may work.
I had also problems in finding something simple to satisfy my needs so I decided to write my own library (with MIT license). It's mainly based on composite and builder pattern.
A basic declarative example is:
A fluent example is:
You can check more examples here
I also created an on line converter to transform every html snippet (from complex bootstrap template to simple single snippet) on the fly (i.e. html -> javatags)
- Works will, very elegant! – Yu Jiaao Nov 30, 2019 at 0:50
- attr("href -> xxx.css",... gives the impression, that the library incurs parsing overhead for writing. Why not attrs(attr("href", "xxx.css"), ...) ? – haui Aug 18, 2020 at 12:51
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:
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...
- Nice idea using only standard tools. Unfortunately, it is tedious to write tHandler.startElement("", "", "p", new AttributesImpl()) - even worse, if one wants to set set a CSS class on an element... – haui Aug 18, 2020 at 12:46
- @haui Well, that was just an idea. It is possible to define some shorthand wrappers around these standard calls to save some typing or copypasting... :) – Sergey Ushakov Aug 18, 2020 at 13:06
If you are willing to use Groovy, the MarkupBuilder is very convenient for this sort of thing, but I don't know that Java has anything like it.
http://groovy.codehaus.org/Creating+XML+using+Groovy 's+MarkupBuilder
if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..

Try the ujo-web library, which supports building HTML pages using the Element class. Here is a sample use case based on a Java servlet:
The servlet generates the next HTML code:
See more information here: https://ujorm.org/www/web/

Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java html or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- how to make a table for describing subsets of rows of another table?
- How would you design the following table?
- Align vertically 2 circuits
- Heap implementation in C
- Is it natural that different quantities with the same physical dimension are distinguished by adverbs?
- how to fix object creating a duplicate of itself during animation?
- Is there a non-constant function on the sphere that diagonalizes all rotations simultaneously?
- Loose bottom bracket on MTB
- MAE to find tuning parameter for lasso logistic regression
- std::to_array for multi dimensional array
- Do new devs get fired if they can't solve a certain bug?
- What is temperature in the classical entropy definition?
- Why did Ukraine abstain from the UNHRC vote on China?
- Linear Algebra - Linear transformation question
- Are people inherently good or bad according to Judaism
- Use of 'nicematrix' for matrices with special annotations
- Euler: “A baby on his lap, a cat on his back — that’s how he wrote his immortal works” (origin?)
- How to tell which packages are held back due to phased updates
- better understanding wash sale rule
- What did Ctrl+NumLock do?
- Precise control of fraction expression
- Are there any other options to mitigate the Volley trait?
- how to replace the diminished chord in a key to write a good song without a diminished chord (for example e diminished to F)?
- When do Yoda's species typically start speaking?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Aspose Knowledge Base
Find advice and answers for most commonly faced scenarios.
Find Answers by API
- Aspose.Total Product Family
- Aspose.Words Product Family
- Aspose.PDF Product Family
- Aspose.Cells Product Family
- Aspose.Email Product Family
- Aspose.Slides Product Family
- Aspose.Imaging Product Family
- Aspose.BarCode Product Family
- Aspose.Diagram Product Family
- Aspose.Tasks Product Family
- Aspose.OCR Product Family
- Aspose.Note Product Family
- Aspose.CAD Product Family
- Aspose.3D Product Family
- Aspose.HTML Product Family
- Aspose.GIS Product Family
- Aspose.ZIP Product Family
- Aspose.Page Product Family
- Aspose.PSD Product Family
- Aspose.OMR Product Family
- Aspose.PUB Product Family
- Aspose.SVG Product Family
- Aspose.Finance Product Family
- Aspose.Drawing Product Family
- Aspose.Font Product Family
- Aspose.TeX Product Family
How to Create HTML File using Java
This topic covers basic implementation of how to create HTML file using Java . You can generate HTML document in Java using simple API calls. HTML files can be generated programmatically on the fly and can be used in different applications like generation of reports or invoices.
Steps to Create HTML file using Java
- Configure your project by adding the Aspose.HTML JAR file from the Maven Repository
- Initialize an empty HTMLDocument object instance
- Add instance of Text element class to hold text for HTML document
- Insert the Text element inside HTML body
- Save the generated HTML file to disk
In order to generate HTML file using Java , first we will create the default HTMLDocument Class instance. Using createTextNode method, we will add desired HTML text for the document. Then we will use Text Class to add the HTML text inside body of HTML. Finally, we will save the HTML document to disk in Java in using simple API calls.
Code to Generate HTML document in Java
In the previous topic, we have learnt how to extract text from DXF file using Java . Whereas this topic in Java create HTML document that can be used for reports or invoices which can be rendered in browsers.
Updated on 26 Dec 2021
HTML in Java

Update: this technique no longer works since name reflection was removed in later versions of Java. Here is another approach. Another use of lambda parameter reflection could be to write html inline in Java. It allows us to create builders like this, in Java, where we’d previously have to use a language like Kotlin and a library like Kara .
String doc = html( head( meta(charset -> "utf-8"), link(rel->stylesheet, type->css, href->"/my.css"), script(type->javascript, src -> "/some.js") ), body( h1("Hello World", style->"font-size:200%;"), article( p("Here is an interesting paragraph"), p( "And another", small("small") ), ul( li("An"), li("unordered"), li("list") ) ) ) ).asString();
Which generates html like
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <meta name="generator" content= "HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net"> <meta charset="utf-8"><script type="text/javascript" src= "/some.js"> </script> <title></title> </head> <body> <h1>Hello World</h1> <p>Here is an interesting paragraph</p> <p>And another<small>small</small></p> <ul> <li>An</li> <li>unordered</li> <li>list</li> </ul> </body> </html>
Code Generation
Why would you do this? Well we could do code generation. e.g. we can programmatically generate paragraphs.
body( asList("one","two","three") .stream() .map(number -> "Paragraph " + number) .map(content -> p(content)) )
Help from the Type System
We can also use the Java type system to help us write valid code.
It will be a compile time error to specify an invalid attribute for link rel.

It’s a compile time error to omit a mandatory tag

It’s also a compile time error to have a body tag inside a p tag, because body is not phrasing content.

We can also ensure that image sizes are in pixels

We can also help reduce injection attacks when inserting content from users into our markup, by having the DSL html-encoding any content passed in.
assertEquals( "<p><script src="attack.js"></script></p>", p("<script src=\"attack.js\"></script>").asString() );
How does it work?
See this previous blogpost that shows how to get lambda parameter names with reflection. This allows us to specify the key value pairs for html attributes quite cleanly.
I’ve created an Attribute type that converts a lambda to a html attribute.
public interface Attribute<T> extends NamedValue<T> { default String asString() { return name() + "=\"" + value()+"\""; } }
For the tags themselves we declare an interface per tag, with a heirarchy to allow certain tags in certain contexts. For example Small is PhrasingContent and can be inside a P tag.
public interface Small extends PhrasingContent { default Small small(String content) { return () -> tag("small", content); } }
To make it easy to have all the tag names available in the context without having to static import lots of things, we can create a “mixin” interface that combines all the tags.
public interface HtmlDsl extends Html, Head, Body, Link, Meta, P, Script, H1, Li, Ul, Article, Small, Img ...
Then where we want to write html we just make our class implement HtmlDsl (Or we could staticly import the methods instead.
We can place restrictions on which tags are valid using overloaded methods for the tag names. e.g. HTML
public interface Html extends NoAttributes { default Html html(Head head, Body body) { ...
and restrict the types of attributes using enums or other wrapper types. Here Img tag can only have measurements in pixels
public interface Img extends NoChildren { default Img img(Attribute<String> src, Attribute<PixelMeasurement> dim1, Attribute<PixelMeasurement> dim2) { ...
All the code is available on github to play with. Have a look at this test for executable examples. n.b. it’s just a proof of concept at this point. Only sufficient code exists to illustrate the examples in this blog post.
What other creative uses can you find for parameter reflection?
Leave a Reply
- Name (required)
- Mail (required) (will not be published)
More Articles
- Do you need a Strong Leader?
- Supporting Sustainability
- Pondering Agile Principles
- Cost of Attrition
- Uncovering Better Ways
- Don’t hire top talent; hire for weaknesses.
- Escape the Permission Trap with Healthy Habits
- Thinking in Questions with SQL
- Leadership Language Lessons from Star Trek
- Java 16 Pattern Matching Fun
- We got lucky
- Revisiting Html in Java
- Meetings, ugh! Let’s change our language
- Latency Numbers Every Team Should Know
- Sealed Java State Machines
- A little rant about talent
- Fun with Java Records
- The benefits of making code worse
- Reasons to hire inexperienced engineers
- Learning from Pain
- The unsung upsides of staying put
- Hack Days; Removing the Rules
- End to End Tests

- An Interview Question
- TECHNOLOGIES
- INTERVIEW PREP

How to Create HTML Editor in Java

- Sandeep Sharma
- Aug 05, 2019
- Other Artcile
This article explains how to create a HTML editor in Java using swing components. This application is GUI based in which we can write HTML code.
Introduction
How to use html tags in swing components.
- btton = new JButton( "<html><b><u>T</u>w<i>o</i></b></html>" );
How to create an HTML Editor in Java
- import java.awt.event.*;
- import javax.swing.*;
- import java.awt.*;
- public class SwingHTMLEditor extends JPanel implements ActionListener
- {
- JTextArea txtArea;
- JLabel labl;
- public SwingHTMLEditor() {
- String htmlText = "<html>\n" +
- "Create table with using different font styles and colors:\n" +
- "<h1>C-#corner.com</h1>\n" +
- "<table border=3 margin=3>\n" +
- "<tr>\n" +
- "<td><font color=red>1</font></td>\n" +
- "<td><font color=blue>2</font></td>\n" +
- "<td><font color=green>3</font></td>\n" +
- "</tr>\n" +
- "<td><font size=-2>4</font></td>\n" +
- "<td><font size=+2>5</font></td>\n" +
- "<td><i>6</i></td>\n" +
- "<td><b>7</b></td>\n" +
- "<td>8</td>\n" +
- "<td>9</td>\n" +
- "</table>" ;
- txtArea = new JTextArea( 20 , 22 );
- setLayout( new BoxLayout( this , BoxLayout.LINE_AXIS));
- txtArea.setText(htmlText);
- JScrollPane scrllPn = new JScrollPane(txtArea);
- JButton lablChngOtpt = new JButton( "Click to change" );
- lablChngOtpt.setMnemonic(KeyEvent.VK_C);
- lablChngOtpt.setAlignmentX(Component.CENTER_ALIGNMENT);
- lablChngOtpt.addActionListener( this );
- labl = new JLabel(htmlText) {
- public Dimension getMaximumSize() {
- return new Dimension( 250 , 250 );
- }
- public Dimension getPreferredSize() {
- public Dimension getMinimumSize() {
- };
- labl.setHorizontalAlignment(SwingConstants.CENTER);
- labl.setVerticalAlignment(SwingConstants.CENTER);
- JPanel panlLeft = new JPanel();
- panlLeft.setLayout( new BoxLayout(panlLeft, BoxLayout.PAGE_AXIS));
- panlLeft.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(
- "Write your own HTML and click the button to see the changes" ),
- BorderFactory.createEmptyBorder( 15 , 15 , 15 , 15 )));
- panlLeft.add(scrllPn);
- panlLeft.add(Box.createRigidArea( new Dimension( 0 , 11 )));
- panlLeft.add(lablChngOtpt);
- JPanel panlRght = new JPanel();
- panlRght.setLayout( new BoxLayout(panlRght, BoxLayout.PAGE_AXIS));
- panlRght.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder( "Swing label with HTML" ),
- panlRght.add(labl);
- setBorder(BorderFactory.createEmptyBorder( 15 , 15 , 15 , 15 ));
- add(panlLeft);
- add(Box.createRigidArea( new Dimension( 11 , 0 )));
- add(panlRght);
- }
- //Perform changes when user click on the button specified.
- public void actionPerformed(ActionEvent e) {
- labl.setText(txtArea.getText());
- private static void showGUI() {
- //Create and set up the window.
- JFrame frm = new JFrame( "SwingHTMLEditor" );
- frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Add content to the window.
- frm.add( new SwingHTMLEditor());
- //Display the window.
- frm.pack();
- frm.setVisible( true );
- public static void main(String[] args) {
- SwingUtilities.invokeLater( new Runnable() {
- public void run() {
- UIManager.put( "swing.boldMetal" , Boolean.FALSE);
- showGUI();
- });
- public class SwingHTMLEditor extends JPanel
- implements ActionListener {
- public SwingHTMLEditor() {
- String htmlText = "<html>\n" +
- "Create table with using different font styles and colors:\n" +
- "<h1>C-#corner.com</h1>\n" +
- "<table border=3 margin=3>\n" +
- "<tr>\n" +
- "<td><font color=red>1</font></td>\n" +
- "<td><font color=blue>2</font></td>\n" +
- "<td><font color=green>3</font></td>\n" +
- "</tr>\n" +
- "<td><font size=-2>4</font></td>\n" +
- "<td><font size=+2>5</font></td>\n" +
- "<td><i>6</i></td>\n" +
- "<td><b>7</b></td>\n" +
- "<td>8</td>\n" +
- "<td>9</td>\n" +
- "</table>" ;
- txtArea = new JTextArea( 20 , 22 );
- setLayout( new BoxLayout( this , BoxLayout.LINE_AXIS));
- txtArea.setText(htmlText);
- JScrollPane scrllPn = new JScrollPane(txtArea);
- JButton lablChngOtpt = new JButton( "Click to change" );
- lablChngOtpt.setMnemonic(KeyEvent.VK_C);
- lablChngOtpt.setAlignmentX(Component.CENTER_ALIGNMENT);
- lablChngOtpt.addActionListener( this );
- labl = new JLabel(htmlText) {
- public Dimension getMaximumSize() {
- return new Dimension( 250 , 250 );
- }
- public Dimension getPreferredSize() {
- public Dimension getMinimumSize() {
- };
- labl.setHorizontalAlignment(SwingConstants.CENTER);
- labl.setVerticalAlignment(SwingConstants.CENTER);
- JPanel panlLeft = new JPanel();
- panlLeft.setLayout( new BoxLayout(panlLeft, BoxLayout.PAGE_AXIS));
- panlLeft.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(
- "Write your own HTML and click the button to see the changes" ),
- BorderFactory.createEmptyBorder( 15 , 15 , 15 , 15 )));
- panlLeft.add(scrllPn);
- panlLeft.add(Box.createRigidArea( new Dimension( 0 , 11 )));
- panlLeft.add(lablChngOtpt);
- JPanel panlRght = new JPanel();
- panlRght.setLayout( new BoxLayout(panlRght, BoxLayout.PAGE_AXIS));
- panlRght.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder( "Swing label with HTML" ),
- panlRght.add(labl);
- setBorder(BorderFactory.createEmptyBorder( 15 , 15 , 15 , 15 ));
- add(panlLeft);
- add(Box.createRigidArea( new Dimension( 11 , 0 )));
- add(panlRght);
- }
- //Perform changes when user click on the button specified.
- public void actionPerformed(ActionEvent e) {
- labl.setText(txtArea.getText());
- private static void showGUI() {
- //Create and set up the window.
- JFrame frm = new JFrame( "SwingHTMLEditor" );
- frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Add content to the window.
- frm.add( new SwingHTMLEditor());
- //Display the window.
- frm.pack();
- frm.setVisible( true );
- public static void main(String[] args) {
- SwingUtilities.invokeLater( new Runnable() {
- public void run() {
- UIManager.put( "swing.boldMetal" , Boolean.FALSE);
- showGUI();
- });

- < html >
- < form >
- First Name: < input type = "text" name = "fname" >
- Last Name: < input type = "text" name = "lname" >
- Create Password: < input type = "password" name = "pass" >
- Confirm Password: < input type = "password" name = "pass" >
- < input type = "submit" value = "submit" >
- < input type = "reset" value = "reset" >

- How to create html editor in java
- HTML Editor
- html tags in swing components
- java html editor
.jpeg)
Solutions Manual to Objects First with Java – A Practical Introduction using BlueJ
Featured articles.

Java Tutorial
Java methods, java classes, java file handling, java how to, java reference, java examples, java create and write to files, create a file.
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):
The output will be:
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the " \ " character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
Run Example »
Advertisement
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:
To read the file above, go to the Java Read Files chapter.

COLOR PICKER

Get your certification today!

Get certified by completing a course today!

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]

Your Suggestion:
Thank you for helping us.
Your message has been sent to W3Schools.
Top Tutorials
Top references, top examples, web certificates, get certified.
- Prev Class
- Next Class
- No Frames
- All Classes
- Summary:
- Nested |
- Field |
- Constr |
- Detail:
Class HTMLDocument
- java.lang.Object
- javax.swing.text.AbstractDocument
- javax.swing.text.DefaultStyledDocument
- javax.swing.text.html.HTMLDocument
The document models only HTML, and makes no attempt to store view attributes in it. The elements are identified by the StyleContext.NameAttribute attribute, which should always have a value of type HTML.Tag that identifies the kind of element. Some of the elements (such as comments) are synthesized. The HTMLFactory uses this attribute to determine what kind of view to build.
This document supports incremental loading. The TokenThreshold property controls how much of the parse is buffered before trying to update the element structure of the document. This property is set by the EditorKit so that subclasses can disable it.
The Base property determines the URL against which relative URLs are resolved. By default, this will be the Document.StreamDescriptionProperty if the value of the property is a URL. If a <BASE> tag is encountered, the base will become the URL specified by that tag. Because the base URL is a property, it can of course be set directly.
The default content storage mechanism for this document is a gap buffer ( GapContent ). Alternatives can be supplied by using the constructor that takes a Content implementation.
Modifying HTMLDocument
In addition to the methods provided by Document and StyledDocument for mutating an HTMLDocument, HTMLDocument provides a number of convenience methods. The following methods can be used to insert HTML content into an existing document.
- setInnerHTML(Element, String)
- setOuterHTML(Element, String)
- insertBeforeStart(Element, String)
- insertAfterStart(Element, String)
- insertBeforeEnd(Element, String)
- insertAfterEnd(Element, String)
The following examples illustrate using these methods. Each example assumes the HTML document is initialized in the following way:
With the following HTML content:
All the methods for modifying an HTML document require an Element . Elements can be obtained from an HTML document by using the method getElement(Element e, Object attribute, Object value) . It returns the first descendant element that contains the specified attribute with the given value, in depth-first order. For example, d.getElement(d.getDefaultRootElement(), StyleConstants.NameAttribute, HTML.Tag.P) returns the first paragraph element.
A convenient shortcut for locating elements is the method getElement(String) ; returns an element whose ID attribute matches the specified value. For example, d.getElement("BOX") returns the DIV element.
The getIterator(HTML.Tag t) method can also be used for finding all occurrences of the specified HTML tag in the document.
Inserting elements
Elements can be inserted before or after the existing children of any non-leaf element by using the methods insertAfterStart and insertBeforeEnd . For example, if e is the DIV element, d.insertAfterStart(e, "<ul><li>List Item</li></ul>") inserts the list before the first paragraph, and d.insertBeforeEnd(e, "<ul><li>List Item</li></ul>") inserts the list after the last paragraph. The DIV block becomes the parent of the newly inserted elements.
Sibling elements can be inserted before or after any element by using the methods insertBeforeStart and insertAfterEnd . For example, if e is the DIV element, d.insertBeforeStart(e, "<ul><li>List Item</li></ul>") inserts the list before the DIV element, and d.insertAfterEnd(e, "<ul><li>List Item</li></ul>") inserts the list after the DIV element. The newly inserted elements become siblings of the DIV element.
Replacing elements
The following table shows the example document and the results of various methods described above.
Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans™ has been added to the java.beans package. Please see XMLEncoder .
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.text. defaultstyleddocument, nested classes/interfaces inherited from class javax.swing.text. abstractdocument, field summary, fields inherited from class javax.swing.text. defaultstyleddocument, fields inherited from class javax.swing.text. abstractdocument, fields inherited from interface javax.swing.text. document, constructor summary, method summary, methods inherited from class javax.swing.text. defaultstyleddocument, methods inherited from class javax.swing.text. abstractdocument, methods inherited from class java.lang. object, methods inherited from interface javax.swing.text. document, field detail, additionalcomments, constructor detail, htmldocument, method detail, insertupdate, setparagraphattributes, getstylesheet, getiterator, createleafelement, createbranchelement, createdefaultroot, settokenthreshold, gettokenthreshold, setpreservesunknowntags, getpreservesunknowntags, processhtmlframehyperlinkevent, setinnerhtml.
This will be seen as at least two events, n inserts followed by a remove.
Consider the following structure (the elem parameter is in bold ).
Invoking setInnerHTML(elem, "<ul><li>") results in the following structure (new elements are in red ).
Parameter elem must not be a leaf element, otherwise an IllegalArgumentException is thrown. If either elem or htmlText parameter is null , no changes are made to the document.
For this to work correctly, the document must have an HTMLEditorKit.Parser set. This will be the case if the document was created from an HTMLEditorKit via the createDefaultDocument method.
setOuterHTML
When replacing a leaf this will attempt to make sure there is a newline present if one is needed. This may result in an additional element being inserted. Consider, if you were to replace a character element that contained a newline with <img> this would create two elements, one for the image, and one for the newline.
If you try to replace the element at length you will most likely end up with two elements, eg setOuterHTML(getCharacterElement (getLength()), "blah") will result in two leaf elements at the end, one representing 'blah', and the other representing the end element.
Invoking setOuterHTML(elem, "<ul><li>") results in the following structure (new elements are in red ).
If either elem or htmlText parameter is null , no changes are made to the document.
insertAfterStart
Invoking insertAfterStart(elem, "<ul><li>") results in the following structure (new elements are in red ).
Unlike the insertBeforeStart method, new elements become children of the specified element, not siblings.
insertBeforeEnd
If elem 's children are leaves, and the character at a elem.getEndOffset() - 1 is a newline, this will insert before the newline so that there isn't text after the newline.
Invoking insertBeforeEnd(elem, "<ul><li>") results in the following structure (new elements are in red ).
Unlike the insertAfterEnd method, new elements become children of the specified element, not siblings.
insertBeforeStart
Invoking insertBeforeStart(elem, "<ul><li>") results in the following structure (new elements are in red ).
Unlike the insertAfterStart method, new elements become siblings of the specified element, not children.
insertAfterEnd
Invoking insertAfterEnd(elem, "<ul><li>") results in the following structure (new elements are in red ).
Unlike the insertBeforeEnd method, new elements become siblings of the specified element, not children.
fireChangedUpdate
Fireundoableeditupdate.
Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation . That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms . Also see the documentation redistribution policy .
Scripting on this page tracks web page traffic, but does not change the content in any way.

- Embedded System
- Interview Q
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

Introduction to HTML
Trevor Page
Learn the Basics of Java Programming
Free java beginners course, an introduction to html….
HTML stands for HyperText Markup Language, and all this really means is that HTML is not a programming language, but rather just a set of rules for structuring your text. This means that if you type out certain words in a particular way, you can create a website! Piece of cake right? For the most part, YES, it is a piece of cake :)
A Basic HTML Example
So to start you off with your introduction to html, let's look at an HTML 101 sort of example. How about we create a webpage that has text on it that just says “Hello World!”. In order to do this, you need to understand the concept of an HTML tag .
HTML tags are the syntax that you use to build your website. All individual webpages are broken up into two main sections:
The HTML Header
The header section of a webpage is where you specify things like the Title of the webpage. If you look at the title of this webpage, you'll see that it says “Introduction to HTML”. This isn't an accident, I used HTML tags to accomplish this.
The HTML Body
The body of a webpage is the real “meat” of the page. This is where all of the useful content goes and where people will actually be interacting with or reading the material. Creating the body is also based on HTML tags.
So let's see what these HTML tags are all about! Here's an example of a webpage that has the words “Hello World!” on it:
So what you see here is the use of lots of HTML tags. These tags are the base, mandatory set of tags that need to be present in order for you to create a webpage. Here's the list of them that are used:
- <html> – Every webpage needs to be wrapped in an ‘html' tag, this is the root element
- <head> – Every webpage also needs a ‘head' tag, this is where you define your title (among other things)
- <title> – You should include the ‘title' tag in order to set the title for the webpage
- <body> – Every webpage needs a ‘body' tag, which outlines all of the actual content that will be displayed
Do you notice how each element has an opening and a closing tag? This is basically the same concept as the scope of a variable in Java (defined by the curly braces {}). In HTML we define the scope of a particular “section” or “element” with these tags. For example, what's the scope of the <html> tag? Well, the first tag in our code is <html> and the LAST tag in our code is </html> . So this means that the html tag encompasses the entire scope of this webpage!
It's important to note that wherever you have an “opening tag” you will also need to include the corresponding “closing tag”. So when you place a <head> tag, you need to remember to insert the corresponding </head> tag as well.
Also, notice how each of the tags are properly nested within each other. What I mean by this is if you inspect any of the tags in our example code (lets pick <head> ), if any new tags are ‘opened', they are subsequently ‘closed' before the </head> tag appears. Like I mentioned before, this is very similar to scoping in Java. So to relate this to Java, you wouldn't create a new method inside of an existing method… you would CLOSE your first method (with a closing curly brace) before you OPENED another method (declared/created a whole new method).
Let's See the Results
If you would like to actually SEE the results of this webpage, all you need to do is create a file on your computer with a “.html” extension and copy/paste our code into it!
Here's how I usually do it:
- Create a file on your desktop (perhaps a regular text file)
- Change the extension to be “.html”, I usually just right-click the file and choose to rename it with “.html” at the end
- Edit the file in your favorite editor (like Notepad++ or STS)
- Copy/Paste in the HTML code from our example above
- Save and open the file!
If all goes well, when you open the file it should open in your default internet browser (I use Google Chrome), and what you'll see is a website with a title and the words “Hello World” like so:
Painless Right?
So there you have it, you've just successfully created a webpage! This is step 1 in your journey to make a fully functional and interactive website. In the next tutorial, I will talk about two things:
- What a ‘doctype' is and why it's important
- How to nicely format your webpage's contents
Because having a webpage with useful information is just half the battle, you will also need to present that information in a way that will keep your audience interested!
Start learning how to code today with our free beginners course. Learn more.
Coders Campus
Launch your coding career..
© 2021 • Crafty Codr Inc • Terms • Privacy
151 Lyndhurst Drive, Kitchener, Ontario N2B 1B7 Canada

IMAGES
VIDEO
COMMENTS
File htmlTemplateFile = new File("path/template.html"); String htmlString = FileUtils.readFileToString(htmlTemplateFile); String title = "New Page"; String
Steps to Create HTML file using Java · Configure your project by adding the Aspose.HTML JAR file from the Maven Repository · Initialize an empty HTMLDocument
How to write an HTML file in java using Eclipse. Sorry about the poor editing in this one.
HTML in Java ; = html( head( meta(charset -> ; ("one","two","three") ; "<p><script src="attack.js"></script></p>", p("<script
How to create an HTML Editor in Java · public SwingHTMLEditor() { · String htmlText = "<html>\n" + · "Create table with using different font styles
HTML and Java are two different things. Java is a programming language, while HTML is just a markup language. While making web pages, HTML is used to make
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java
A document that models HTML. The purpose of this model is to support both browsing and editing. As a result, the structure described by an HTML document is
Step 2 - Now, start writing HTML programs in the text editor. The HTML tags are enclosed within open tags (<>) and closed tags (</>). Suppose we have to create
HTML stands for HyperText Markup Language, and all this really means is that HTML is not a programming language, but rather just a set of rules for structuring