|
Java™ by example!
|
|
|
How do I convert source code to HTML?
It is nontrivial to display code in an HTML page. It is not sufficient to use <pre> and </pre> around your source code to ensure it is displayed correctly. These following characters need to be converted to their corresponding HTML code: < , > , & and ".
This program converts the inputfile so that it can be displayed on an HTML page. The output is redirected to the standard outputstream.
 import java.io.*;
public class Code2Html { public static void main(String args[]) { if (args.length != 1) { System.err.println("usage: java Code2Html file.java > file.html"); System.exit(1); }
try { StringBuffer file = readTextFile(args[0]); System.out.println(code2Html(file)); } catch(Exception e) { System.out.println(e); } } public static StringBuffer code2Html(StringBuffer code) { StringBuffer sb = new StringBuffer(); for (int i=0; i<code.length(); i++) { char c = code.charAt(i); switch(c) { case '<': sb.append("<"); break; case '>': sb.append("&gr;"); break; case '&': sb.append("&"); break; case '"': sb.append("""); break; default : sb.append(c); } }
return sb; } public static StringBuffer readTextFile(String filename) throws Exception { StringBuffer total = new StringBuffer(); FileReader in = new FileReader(filename); char [] buf = new char[512]; int howmany; while ((howmany = in.read(buf)) >= 0) { total.append(buf, 0, howmany); } in.close(); return total; } }
|
Further Information
Author of answer: unknown
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|