First, the format of the markup language needs to be explained. The first line will be a title, and then subsequent paragraphs are blank-line separated. This can be translated into an HTML file as follows.
Minimark source |
Translated HTML |
---|---|
This is the title A paragraph with some text Another paragraph |
<html><head><title>This is the title</title></head><body><h1>This is the title</h1> <p> A paragraph with some text </p> <p> Another paragraph </p></body></html> |
MinimarkTranslator
in the com.packtpub.e4.minimark.ui
package as follows:public class MinimarkTranslator { public static void convert(Reader reader, Writer writer) throws IOException { BufferedReader lines = new BufferedReader(reader); String line; String title = String.valueOf(lines.readLine()); writer.write("<html><head><title>"); writer.write(title); writer.write("</title></head><body><h1>"); writer.write("</h1><p>"); while (null != (line = lines.readLine())) { if ("".equals(line)) { writer.write("</p><p>"); } else { writer.write(line); writer.write(' '); } } writer.write("</p></body></html>"); writer.flush(); } }
in.txt
in the com.packtpub.e4.minimark.ui
project.main
method to the MinimarkTranslator
to read in the in.txt
file and write it out as out.txt
:public static void main(String[] args) throws IOException { convert( new FileReader("in.txt"), new FileWriter("out.txt")); }
out.txt
should be shown, and opening it should show an HTML file like the one at the start of this section.MinimarkConverter
works as expected, delete the main
method.The minimal markup language can take plain ASCII text and translate it into an HTML file. The purpose of this exercise is not to define a fully comprehensive markup processor, but rather to provide a simple translator that can be shown to generate HTML as rendered in a browser from a plain text file.
The reader is invited to replace the translator with a different implementation, such as one of the Markdown parsers available on GitHub or Maven Central.
18.225.209.95