一个String显示在网页上,不会安置原来的格式显示,比如说,回车符在网页上就显示成了一个空格,
下面这个方法可以将String改为HTML可以辨认的格式。
public static String toHTMLString(String in) {
        StringBuffer out = new StringBuffer();
        for (int i = 0; in != null && i < in.length(); i++) {
            char c = in.charAt(i);
            if (c == '\'')
                out.append("&#039;");
            else if (c == '\"')
                out.append("&#034;");
            else if (c == '<')
                out.append("&lt;");
            else if (c == '>')
                out.append("&gt;");
            else if (c == '&')
                out.append("&amp;");
            else if (c == ' ')
                out.append("&nbsp;");
            else if (c == '\n')
                out.append("<br/>");
            else
                out.append(c);
        }
        return out.toString();
    }
具体请查看http://blog.csdn.net/sunlen/archive/2005/02/02/278238.aspx

解决方案 »

  1.   

    存入数据库的时候加<br>应该也可以
      

  2.   

    但是如果把某些文章存入数据库会导致字符转换,例如文章内容如下:
    public static String toHTMLString(String in) {
            StringBuffer out = new StringBuffer();
            for (int i = 0; in != null && i < in.length(); i++) {
                char c = in.charAt(i);
                if (c == '\'')
                    out.append("&#039;");
                else if (c == '\"')
                    out.append("&#034;");
                else if (c == '<')
                    out.append("&lt;");
                else if (c == '>')
                    out.append("&gt;");
                else if (c == '&')
                    out.append("&amp;");
                else if (c == ' ')
                    out.append("&nbsp;");
                else if (c == '\n')
                    out.append("<br/>");
                else
                    out.append(c);
            }
            return out.toString();
        }
    不知道谁知道怎么办?
      

  3.   

    大意了,大意了,原来以上代码也可以用toHTMLString(String in)转换,看来要三思而行之!