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:
BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("<html><head><title>New Page</title></head><body><p>This is Body</p></body></html>"); bw.close();
Is there any easier way to do this, as I have to create tables and it is becoming very inconvenient?
Put a tag like $tag for any dynamic content and then do something like this: File htmlTemplateFile = new File("path/template. html"); String htmlString = FileUtils. readFileToString(htmlTemplateFile); String title = "New Page"; String body = "This is Body"; htmlString = htmlString.
To create a new HTML file: In PHP Explorer view, select the folder into which you would like to create the file and from the Menu Bar go to File | New | HTML Page -or- right-click the folder and select File | New | HTML. Page. The new HTML Page dialog will appear.
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:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>$title</title> </head> <body>$body </body> </html>
Put a tag like $tag
for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html"); String htmlString = FileUtils.readFileToString(htmlTemplateFile); String title = "New Page"; String body = "This is Body"; htmlString = htmlString.replace("$title", title); htmlString = htmlString.replace("$body", body); File newHtmlFile = new File("path/new.html"); FileUtils.writeStringToFile(newHtmlFile, htmlString);
Note: I used org.apache.commons.io.FileUtils for simplicity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With