科帮网-Java论坛、Java社区、JavaWeb毕业设计

登录/注册
您现在的位置:论坛 盖世程序员(我猜到了开头 却没有猜到结局) 运维优化 > 数据库html转为text文本内容并保留格式
总共48086条微博

动态微博

查看: 2288|回复: 0

数据库html转为text文本内容并保留格式

[复制链接]
admin    

1244

主题

544

听众

1万

金钱

管理员

  • TA的每日心情

    2021-2-2 11:21
  • 签到天数: 36 天

    [LV.5]常住居民I

    管理员

    跳转到指定楼层
    楼主
    发表于 2014-04-21 20:36:15 |只看该作者 |倒序浏览
    1. package javaOrJs;
    2. import java.io.BufferedWriter;
    3. import java.io.FileWriter;
    4. import java.util.HashMap;
    5. import java.util.Map;

    6. /**
    7. * Copyright (c) 2010-2013 by 52itstyle
    8. * All rights reserved.
    9. */

    10. /**
    11. *@Function: html 转为纯文本 保留格式
    12. *@Class Name: WebFormatter
    13. *@Author: zhangZhiPeng
    14. *@Date: 2013-10-29
    15. *@Modifications:
    16. *@Modifier Name; Date; The Reason for Modifying
    17. *
    18. */
    19. public class WebFormatter{
    20.          public static void main(String[] args){
    21.                  String content = html2text("<p>The Nobel(璇鸿礉灏? Peace Prize for 2008 was given to Martti Ahtisaari. He was the president of Finland from 1994 to 2000. He won the prize for his work in solving (瑙e喅)international conflicts (鍐茬獊) for more than 30 years. </p><p>   During all his life, both as president and as an international officer, he has worked for peace. For the past 20 years, he has done a lot to resolve several serious international conflicts. Some of these conflicts had lasted for years. In 1989-90, he played an important role in helping Namibia鈥檚 independence(鐙?珛); in 2005 he did his best to help solve the Aceh question in Indonesia. In 1999 and again in 2005-2007, under very difficult situation he found ways to help solve the conflict in Kosovo. In 2008, together with other organizations, he has tried to help solve many of the problems in Iraq. He has also made great contributions(璐$尞) to solving the conflict in Northern Ireland, Central Asia, and on the Horn of Africa.</p><p>    鈥淭his work has made a more peaceful world in Nobel鈥檚 spirit,鈥?the officer said, 鈥渟o he has won the prize.鈥?</p>");
    22.                     System.out.println(content);
    23.                     String txtSrc = "D://tomcat6_beta//webapps//web01//file//paper//111.txt";
    24.                     createTextFile(txtSrc,content);
    25.             }
    26.          public static void createTextFile(String src, String text) {
    27.                    try {
    28.                            FileWriter fw = new FileWriter(src);
    29.                            BufferedWriter bw = new BufferedWriter(fw);
    30.                            bw.write(text);
    31.                            bw.flush();
    32.                            bw.close();
    33.                            fw.close();
    34.                         } catch (Exception e) {
    35.                                 e.printStackTrace();
    36.                         }
    37.            }
    38.           public static String html2text(String html) {
    39.                 StringBuffer sb = new StringBuffer(html.length());
    40.                 char[] data = html.toCharArray();
    41.                 int start = 0;
    42.                 boolean previousIsPre = false;
    43.                 Token token = null;
    44.                 for(;;) {
    45.                     token = parse(data, start, previousIsPre);
    46.                     if(token==null)
    47.                         break;
    48.                     previousIsPre = token.isPreTag();
    49.                     sb = sb.append(token.getText());
    50.                     start += token.getLength();
    51.                 }
    52.                 return sb.toString();
    53.             }

    54.             private static Token parse(char[] data, int start, boolean previousIsPre) {
    55.                 if(start>=data.length)
    56.                     return null;
    57.                 // try to read next char:
    58.                 char c = data[start];
    59.                 if(c=='<') {
    60.                     // this is a tag or comment or script:
    61.                     int end_index = indexOf(data, start+1, '>');
    62.                     if(end_index==(-1)) {
    63.                         // the left is all text!
    64.                         return new Token(Token.TOKEN_TEXT, data, start, data.length, previousIsPre);
    65.                     }
    66.                     String s = new String(data, start, end_index-start+1);
    67.                     // now we got s="<...>":
    68.                     if(s.startsWith("<!--")) { // this is a comment!
    69.                         int end_comment_index = indexOf(data, start+1, "-->");
    70.                         if(end_comment_index==(-1)) {
    71.                             // illegal end, but treat as comment:
    72.                             return new Token(Token.TOKEN_COMMENT, data, start, data.length, previousIsPre);
    73.                         }
    74.                         else
    75.                             return new Token(Token.TOKEN_COMMENT, data, start, end_comment_index+3, previousIsPre);
    76.                     }
    77.                     String s_lowerCase = s.toLowerCase();
    78.                     if(s_lowerCase.startsWith("<script")) { // this is a script:
    79.                         int end_script_index = indexOf(data, start+1, "</script>");
    80.                         if(end_script_index==(-1))
    81.                             // illegal end, but treat as script:
    82.                             return new Token(Token.TOKEN_SCRIPT, data, start, data.length, previousIsPre);
    83.                         else
    84.                             return new Token(Token.TOKEN_SCRIPT, data, start, end_script_index+9, previousIsPre);
    85.                     }
    86.                     else { // this is a tag:
    87.                         return new Token(Token.TOKEN_TAG, data, start, start+s.length(), previousIsPre);
    88.                     }
    89.                 }
    90.                 // this is a text:
    91.                 int next_tag_index = indexOf(data, start+1, '<');
    92.                 if(next_tag_index==(-1))
    93.                     return new Token(Token.TOKEN_TEXT, data, start, data.length, previousIsPre);
    94.                 return new Token(Token.TOKEN_TEXT, data, start, next_tag_index, previousIsPre);
    95.             }

    96.             private static int indexOf(char[] data, int start, String s) {
    97.                 char[] ss = s.toCharArray();
    98.                 // TODO: performance can improve!
    99.                 for(int i=start; i<(data.length-ss.length); i++) {
    100.                     // compare from data[i] with ss[0]:
    101.                     boolean match = true;
    102.                     for(int j=0; j<ss.length; j++) {
    103.                         if(data[i+j]!=ss[j]) {
    104.                             match = false;
    105.                             break;
    106.                         }
    107.                     }
    108.                     if(match)
    109.                         return i;
    110.                 }
    111.                 return (-1);
    112.             }

    113.             private static int indexOf(char[] data, int start, char c) {
    114.                 for(int i=start; i<data.length; i++) {
    115.                     if(data[i]==c)
    116.                         return i;
    117.                 }
    118.                 return (-1);
    119.             }

    120.         }

    121.         @SuppressWarnings("unchecked")
    122.         class Token {

    123.             public static final int TOKEN_TEXT    = 0; // html text.
    124.             public static final int TOKEN_COMMENT = 1; // comment like <!-- comments... -->
    125.             public static final int TOKEN_TAG     = 2; // tag like <pre>, <font>, etc.
    126.             public static final int TOKEN_SCRIPT  = 3;

    127.             private static final char[] TAG_BR  = "<br".toCharArray();
    128.             private static final char[] TAG_P   = "<p".toCharArray();
    129.             private static final char[] TAG_LI  = "<li".toCharArray();
    130.             private static final char[] TAG_PRE = "<pre".toCharArray();
    131.             private static final char[] TAG_HR  = "<hr".toCharArray();

    132.             private static final char[] END_TAG_TD = "</td>".toCharArray();
    133.             private static final char[] END_TAG_TR = "</tr>".toCharArray();
    134.             private static final char[] END_TAG_LI = "</li>".toCharArray();

    135.             private static final Map SPECIAL_CHARS = new HashMap();

    136.             private int type;
    137.             private String html;           // original html
    138.             private String text = null;    // text!
    139.             private int length = 0;        // html length
    140.             private boolean isPre = false; // isPre tag?

    141.             static {
    142.                 SPECIAL_CHARS.put(""", "/");
    143.                 SPECIAL_CHARS.put("<",   "<");
    144.                 SPECIAL_CHARS.put(">",   ">");
    145.                 SPECIAL_CHARS.put("&",  "&");
    146.                 SPECIAL_CHARS.put("®",  "(r)");
    147.                 SPECIAL_CHARS.put("©", "(c)");
    148.                 SPECIAL_CHARS.put(" ", " ");
    149.                 SPECIAL_CHARS.put("£", "?");
    150.             }

    151.             public Token(int type, char[] data, int start, int end, boolean previousIsPre) {
    152.                 this.type = type;
    153.                 this.length = end - start;
    154.                 this.html = new String(data, start, length);
    155.                 //System.out.println("[Token] html=" + html + ".");
    156.                 parseText(previousIsPre);
    157.                 // System.out.println("[Token] text=" + text + ".");
    158.             }

    159.             public int getLength() {
    160.                 return length;
    161.             }

    162.             public boolean isPreTag() {
    163.                 return isPre;
    164.             }

    165.             private void parseText(boolean previousIsPre) {
    166.                 if(type==TOKEN_TAG) {
    167.                     char[] cs = html.toCharArray();
    168.                     if(compareTag(TAG_BR, cs) || compareTag(TAG_P, cs))
    169.                         text = "\r\n";
    170.                     else if(compareTag(TAG_LI, cs))
    171.                         text = "\n* ";
    172.                     else if(compareTag(TAG_PRE, cs))
    173.                         isPre = true;
    174.                     else if(compareTag(TAG_HR, cs))
    175.                         text = "\n--------\n";
    176.                     else if(compareString(END_TAG_TD, cs))
    177.                         text = "\t";
    178.                     else if(compareString(END_TAG_TR, cs) || compareString(END_TAG_LI, cs))
    179.                         text = "\n";
    180.                 }
    181.                 // text token:
    182.                 else if(type==TOKEN_TEXT) {
    183.                     text = toText(html, previousIsPre);
    184.                 }
    185.             }

    186.             public String getText() {
    187.                 return text==null ? "" : text;
    188.             }

    189.             private String toText(String html, final boolean isPre) {
    190.                 char[] cs = html.toCharArray();
    191.                 StringBuffer buffer = new StringBuffer(cs.length);
    192.                 int start = 0;
    193.                 boolean continueSpace = false;
    194.                 char current, next;
    195.                 for(;;) {
    196.                     if(start>=cs.length)
    197.                         break;
    198.                     current = cs[start]; // read current char
    199.                     if(start+1<cs.length) // and next char
    200.                         next = cs[start+1];
    201.                     else
    202.                         next = '\0';
    203.                     if(current==' ') {
    204.                         if(isPre || !continueSpace)
    205.                             buffer = buffer.append(' ');
    206.                         continueSpace = true;
    207.                         // continue loop:
    208.                         start++;
    209.                         continue;
    210.                     }
    211.                     // not ' ', so:
    212.                     if(current=='\r' && next=='\n') {
    213.                         if(isPre)
    214.                             buffer = buffer.append('\n');
    215.                         // continue loop:
    216.                         start+=2;
    217.                         continue;
    218.                     }
    219.                     if(current=='\n' || current=='\r') {
    220.                         if(isPre)
    221.                             buffer = buffer.append('\n');
    222.                         // continue loop:
    223.                         start++;
    224.                         continue;
    225.                     }
    226.                     // cannot continue space:
    227.                     continueSpace = false;
    228.                     if(current=='&') {
    229.                         // maybe special char:
    230.                         int length = readUtil(cs, start, ';', 10);
    231.                         if(length==(-1)) { // just '&':
    232.                             buffer = buffer.append('&');
    233.                             // continue loop:
    234.                             start++;
    235.                             continue;
    236.                         }
    237.                         else { // check if special character:
    238.                             String spec = new String(cs, start, length);
    239.                             String specChar = (String)SPECIAL_CHARS.get(spec);
    240.                             if(specChar!=null) { // special chars!
    241.                                 buffer = buffer.append(specChar);
    242.                                 // continue loop:
    243.                                 start+=length;
    244.                                 continue;
    245.                             }
    246.                             else { // check if like 'Ӓ':
    247.                                 if(next=='#') { // maybe a char
    248.                                     String num = new String(cs, start+2, length-3);
    249.                                     try {
    250.                                         int code = Integer.parseInt(num);
    251.                                         if(code>0 && code<65536) { // this is a special char:
    252.                                             buffer = buffer.append((char)code);
    253.                                             // continue loop:
    254.                                             start++;
    255.                                             continue;
    256.                                         }
    257.                                     }
    258.                                     catch(Exception e) {}
    259.                                     // just normal char:
    260.                                     buffer = buffer.append("&#");
    261.                                     // continue loop:
    262.                                     start+=2;
    263.                                     continue;
    264.                                 }
    265.                                 else { // just '&':
    266.                                     buffer = buffer.append('&');
    267.                                     // continue loop:
    268.                                     start++;
    269.                                     continue;
    270.                                 }
    271.                             }
    272.                         }
    273.                     }
    274.                     else { // just a normal char!
    275.                         buffer = buffer.append(current);
    276.                         // continue loop:
    277.                         start++;
    278.                         continue;
    279.                     }
    280.                 }
    281.                 return buffer.toString();
    282.             }

    283.             // read from cs[start] util meet the specified char 'util',
    284.             // or null if not found:
    285.             private int readUtil(final char[] cs, final int start, final char util, final int maxLength) {
    286.                 int end = start+maxLength;
    287.                 if(end>cs.length)
    288.                     end = cs.length;
    289.                 for(int i=start; i<start+maxLength; i++) {
    290.                     if(cs[i]==util) {
    291.                         return i-start+1;
    292.                     }
    293.                 }
    294.                 return (-1);
    295.             }

    296.             // compare standard tag "<input" with tag "<INPUT value=aa>"
    297.             private boolean compareTag(final char[] ori_tag, char[] tag) {
    298.                 if(ori_tag.length>=tag.length)
    299.                     return false;
    300.                 for(int i=0; i<ori_tag.length; i++) {
    301.                     if(Character.toLowerCase(tag[i])!=ori_tag[i])
    302.                         return false;
    303.                 }
    304.                 // the following char should not be a-z:
    305.                 if(tag.length>ori_tag.length) {
    306.                     char c = Character.toLowerCase(tag[ori_tag.length]);
    307.                     if(c<'a' || c>'z')
    308.                         return true;
    309.                     return false;
    310.                 }
    311.                 return true;
    312.             }

    313.             private boolean compareString(final char[] ori, char[] comp) {
    314.                 if(ori.length>comp.length)
    315.                     return false;
    316.                 for(int i=0; i<ori.length; i++) {
    317.                     if(Character.toLowerCase(comp[i])!=ori[i])
    318.                         return false;
    319.                 }
    320.                 return true;
    321.             }

    322.             public String toString() {
    323.                 return html;
    324.             }

    325. }
    复制代码





    科帮网-Java论坛、Java社区、JavaWeb毕业设计 1、本主题所有言论和图片纯属会员个人意见,与本社区立场无关
    2、本站所有主题由该帖子作者发表,该帖子作者与科帮网-Java论坛、Java社区、JavaWeb毕业设计享有帖子相关版权
    3、其他单位或个人使用、转载或引用本文时必须同时征得该帖子作者和科帮网-Java论坛、Java社区、JavaWeb毕业设计的同意
    4、帖子作者须承担一切因本文发表而直接或间接导致的民事或刑事法律责任
    5、本帖部分内容转载自其它媒体,但并不代表本站赞同其观点和对其真实性负责
    6、如本帖侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意
    7、科帮网-Java论坛、Java社区、JavaWeb毕业设计管理员和版主有权不事先通知发贴者而删除本文


    JAVA爱好者①群:JAVA爱好者① JAVA爱好者②群:JAVA爱好者② JAVA爱好者③ : JAVA爱好者③

    红红火火恍恍惚惚
    快速回复
    您需要登录后才可以回帖 登录 | 立即注册

       

    发布主题 快速回复 返回列表 联系我们 官方QQ群 科帮网手机客户端
    快速回复 返回顶部 返回列表