这一节主要讲的把网页上的内容转换成html格式才好存入到数据库中并主类,
这个类叫CodeFilter类,内容如下:
package com.ppcms.common; public class CodeFilter { public CodeFilter(){ } public static String toHtml(String s) { if(s == null){ s = ""; return s; }else{ s = Replace(s.trim(), "&", "&"); s = Replace(s.trim(), "<", "<"); s = Replace(s.trim(), ">", ">"); s = Replace(s.trim(), "\t", " "); s = Replace(s.trim(), "\r\n", "\n"); s = Replace(s.trim(), "\n", "<br>"); s = Replace(s.trim(), " ", " "); s = Replace(s.trim(), "'", "'"); s = Replace(s.trim(), "\\", "\"); } return s; // 有的人会说能替换吗,S不是String的吗,不可以改变的吗。 // 其实,这里的每个S都不是原来的S。而是在执行Replace时返回的out.toString()这个字符串。 } public static String toUbbHtml(String s) { if(s == null){ s = ""; return s; }else{ s = Replace(s, "\n", "<br>"); s = Replace(s, " ", " "); s = Replace(s, "'", "'"); s = Replace(s, "\\", "\"); return s; } } public static String unHtml(String s) { s = Replace(s, "<br>", "\n"); s = Replace(s, " ", " "); return s; } public static String Replace(String source,String oldStr,String newStr) { StringBuffer out = new StringBuffer(); int sourceLength = source.length(); int oldStrLength = oldStr.length(); int posStart; int i; for(posStart = 0;((i = source.indexOf(oldStr,posStart))>=0);posStart = i + oldStrLength){ // 新建一个StringBuffer out来存放替换后的新的字符串, // 从source字符串的开头开始,查找是否有需要替换的字符串(oldStr) // (i = source.indexOf(oldStr,posStart))>0表示source中是否有需替换的字符串,有返回它的起始地址, // 然后从起始点到找到的需替换字符串的位置形成一个子串,放到新的out StringBuffer中。然后再把新内容添加到out中去。 // 然后在source中跳过需查找的内容再次进行,下一次查找。 // 最终形成的out字符串就是原source字符串,把需替换的oldStr 替换成的新的newStr字符串。 out.append(source.substring(posStart, i)); out.append(newStr); } if(posStart < sourceLength) out.append(source.substring(posStart)); return out.toString(); } }这里的类主要有两个方法,第一个是静态Replace方法
返回:<title>Blog - MY's proson web- & Open Source </title>Blog \t MY's like! \n and I Love You !
package com.ppcms.common; import java.io.*; import java.util.Scanner; public class TestCodeFilter { public static void main(String args[]) { InputStreamReader(System.in)); System.out.println("请输入字符串:"); Scanner in = new Scanner(System.in); String input = in.nextLine(); String csStr = CodeFilter.toHtml(input); System.out.println("\n---------------------------------------------------------------"); System.out.println("下面是返回的字符串:"); System.out.println(csStr); } }执行结果:
请输入字符串: <title>Blog - MY's proson web- & Open Source </title>Blog \t MY's like! \n and I Love You ! --------------------------------------------------------------- 下面是返回的字符串: <title>Blog - MY's proson web- & Open Source </title>Blog \t MY's like! \n and I Love You !这个以类以后在做JavaWeb时应该用得到。