esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

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("&lt;"); break;
case '>': sb.append("&gr;"); break;
case '&': sb.append("&amp;"); break;
case '"': sb.append("&quot;"); 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!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.