Thursday, December 11, 2008

Posting copy-able code in a blog

I ran into a problem where I could not put code into blog entries. So, after much research, I found that:

1. Make sure the maximum number of characters without spaces is 80. Anything else will be wrapped and lost

2. To add code (Java / C++ / C# etc.) in your blob entry, "Edit Html", and enclose the code in:

<pre style="font-size: 90%;"><code>
--- PASTE CODE HERE ----
</code></pre>

3. To Embed / insert xml code into html / blog entry, you must get rid of all of these characters from XML and replace then with their equivalent HTML friendly format: '<', '>', '&'. For a pretty display, I also converted all tabs to 4 spaces. Here is Java code that helped me do just that:

import java.io.FileReader;

public class ConvertToHtml {

public static void main(String[] args) throws Exception {
if (args.length != 1) {
usage();
return;
}

FileReader fr = new FileReader(args[0]);
int c;
while ((c = fr.read()) != -1) {
if (c == '<') {
System.out.print("<");
}
else if (c == '>') {
System.out.print(">");
}
else if (c == '&') {
System.out.print("&");
}
else if (c == '\t') {
System.out.print(" "); // 4 spaces to a tab
}
else {
System.out.print((char) c);
}
}
fr.close();
}

private static void usage() {
System.out.println("This util converts input to html safe code");
System.out.println("Please pass one and only one argument: file that needs converting. Output will be sent to stdout");
}

}


Hope this helps. Please do post a comment, if you use some other way to make blog entries code friendly.

1 comment:

  1. This is definitely one of the best articles I have read in this website! Thanks Mate.
    java training in Chennai

    ReplyDelete