Scribblin.gs
a blob   Software

Entity Encoder

EntityEncoder provides Java programmers with an easy way to encode text characters into HTML character entities as defined by http://www.w3.org/TR/REC-html40/sgml/entities.html. It is intended for programmers writing web applications,who need to ensure that text sent to web browsers does not contain HTML control characters (e.g. a literal '<') and that typographic symbols (e.g. '©') display properly. The EntityEncoder can convert characters into entity names or into numeric entity codes. The Entity Encoder understands all of the character entities referenced in the above-mentioned W3 specification. This includes:

The Entity Encoder provides static methods for converting strings or single characters into entities, and a Writer that can be used to filter streaming text. Thanks to a contribution by Vijaraghavan Kalyanapasupathy, typographic symbols can be referred to by symbolic names (e.g. "Phi") as well as by their Unicode representation.

The two use patterns (method calling and stream filtering) are demonstrated in the example program below.

package gs.scribblin.entityEncoder;
import java.io.*;

/**
 * Using the Entity Encoder
 */
public class EncodeThings
{
    public static void main(String[] args)
    throws IOException
    {
        // Use the static methods of Encoder
        // to convert strings.
        String s = "My osprey is called \"\".";
	    s +=  " It is worth \u00A3 5";
        System.out.println("Original:\n " + s);
        System.out.println(
	      "Entity encoded:\n " + Encoder.encode(s)
        );
        System.out.println(
            "Numeric encoding:\n  " + Encoder.encodeNumeric(s)
        );
        
        // Use the writer to encode a stream of text.
        System.out.print("Type something to encode:");
        System.out.println("(\"QUIT\" to finish)");
        Writer filt =
	    Encoder.createWriter(new PrintWriter(System.out));
        BufferedReader br = new BufferedReader(
            new InputStreamReader(System.in)
        );
        String line;
        while (!(line = br.readLine()).equals("QUIT")) {
            filt.write(line + "\n");
        }
        br.close();
        filt.close();
    }
}

To use the Entity Encoder, add entityEncoder.jar to your classpath and import gs.scribblin.entityEncoder into your source file. Further details may be found in the JavaDoc documentation.

The Entity Encoder is released under the terms of the GNU General Public Licence Version 2.

Download entityEncoder.jar
Download the JavaDocs
Download source code