• 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?

hoshang.varshney's user avatar

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.

Marco Lackovic's user avatar

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:

Miguel Gamboa's user avatar

You can use jsoup or wffweb (HTML5) based.

Sample code for jsoup:-

Sample code for wffweb:-

prints (in minified format):-

RRadley's user avatar

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.

PATRY Guillaume's user avatar

I would highly recommend you use a very simple templating language such as Freemarker

npellow's user avatar

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 cons are:

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.

Arseni Mourzenko's user avatar

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)

M. Modugno's user avatar

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...

Sergey Ushakov's user avatar

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

Eric Wilson's user avatar

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..

Chani's user avatar

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/

pop's user avatar

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 .

Hot Network Questions

how to write html in java

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

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

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

benji

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.

how to write html in java

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

how to write html in java

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

how to write html in java

We can also ensure that image sizes are in pixels

how to write html in java

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>&lt;script src=&quot;attack.js&quot;&gt;&lt;/script&gt;</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

More Articles

C# Corner

Java

How to Create HTML Editor in Java

how to write html in java

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.

How to create an HTML Editor in Java

fig-1.jpg

Fig-3.jpg

C# Corner Ebook

Solutions Manual to Objects First with Java – A Practical Introduction using BlueJ

Featured articles.

Learn

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.

Get started with your own server with Dynamic Spaces

COLOR PICKER

colorpicker

Get your certification today!

how to write html in java

Get certified by completing a course today!

Subscribe

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.

Class 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.

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.

Javatpoint Logo

JavaTpoint

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

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

RSS Feed

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:

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:

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:

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

  1. Format java code in HTML to display it like in an IDE

    how to write html in java

  2. What is algorithm to complete the missing HTML start tag in Java?

    how to write html in java

  3. Write HTML file in Java

    how to write html in java

  4. Can we write a Java code without main method?

    how to write html in java

  5. How to use packages in Java? How would you explain it with an example

    how to write html in java

  6. java

    how to write html in java

VIDEO

  1. Writing Basic Html

  2. Javascript Class 001

  3. Java_2_1.flv

  4. What Java is to JavaScript #webdevelopment #programming #javascript

  5. Write the program to print the square of any number || Java || AKcoder

  6. 3- JavaScript Tutorial for Beginners

COMMENTS

  1. Write HTML file using Java

    File htmlTemplateFile = new File("path/template.html"); String htmlString = FileUtils.readFileToString(htmlTemplateFile); String title = "New Page"; String

  2. How to Create HTML File using Java

    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

  3. Write HTML file in Java

    How to write an HTML file in java using Eclipse. Sorry about the poor editing in this one.

  4. HTML in Java

    HTML in Java ; = html( head( meta(charset -> ; ("one","two","three") ; "<p>&lt;script src=&quot;attack.js&quot;&gt;&lt;/script&gt;</p>", p("<script

  5. How to Create HTML Editor in Java

    How to create an HTML Editor in Java · public SwingHTMLEditor() { · String htmlText = "<html>\n" + · "Create table with using different font styles

  6. How should one write HTML code in Java?

    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

  7. Java Create and Write To Files

    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

  8. HTMLDocument (Java Platform SE 8 )

    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

  9. How to write HTML

    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

  10. 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