Time for action – writing the markup parser

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>
  1. Create a class called 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();
      }
    }
  2. Copy the example text from the start of this section and save it as a file in.txt in the com.packtpub.e4.minimark.ui project.
  3. Add a 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"));
    }
  4. Run this as a Java application, and refresh the project. The file out.txt should be shown, and opening it should show an HTML file like the one at the start of this section.
  5. After testing that the MinimarkConverter works as expected, delete the main method.

What just happened?

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.

Note

Note that the translator has at least one bug; if the file is empty, then the title may well be null, which would result in a title of null in the HTML browser.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.209.95