告別文章摘要的煩惱之博客系統

package com.chendaojun.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ParseHtml { public static void main(String[] args){ //可以將註釋打開逐個試驗 ParseHtml ph = new ParseHtml(); String html=""; //打開下面兩行可進行連接mysql並解析html //html=ph.getHtmlFromMysql(); //System.out.println(ph.parseHtml(html)); //System.out.println(ph.parseHtml(html,300)); //打開下面兩行可進行獲得路徑文件內容並解析html,路徑根據實際修改 //html=ph.getHtml("E:\\1478300.html"); //System.out.println(ph.parseHtml(html)); //System.out.println(ph.parseHtml(html,300)); //指定長度直接解析 //html=ph.parseHtml("<p>sdfsdf</p><br><div>sdfsdfsdf</div>",10); //System.out.println(html); //直接解析 html=ph.parseHtml("<p>sdfsdf</p><br><div>sdfsdfsdf</div>sdflksdflksdjfk<dkf"); System.out.println(html); } //從mysql中取出在線編輯器存進去的html文章 public String getHtmlFromMysql(){ String url="jdbc:mysql://localhost:3306/blog"; String userName="root"; String passWord="root"; String className="com.mysql.jdbc.Driver"; String sql="select text from blog where id=5"; String html=""; Connection conn=null; Statement stmt=null; ResultSet rs=null; try{ Class.forName(className); conn=DriverManager.getConnection(url,userName,passWord); stmt=conn.createStatement(); rs=stmt.executeQuery(sql); while(rs.next()){ //獲得html內容 html=rs.getString("text"); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(rs!=null){ rs.close(); rs=null; } if(stmt!=null){ stmt.close(); stmt=null; } if(conn!=null){ conn.close(); conn=null; } }catch(Exception e){ e.printStackTrace(); } } return html; } //從指定路徑讀取html文件 public String getHtml(String filePath) { String html = ""; FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; try { File file = new File(filePath); fis = new FileInputStream(file); isr = new InputStreamReader(fis); br = new BufferedReader(isr); String bRead = ""; while ((bRead = br.readLine()) != null) { html += bRead; } } catch (Exception e) { e.printStackTrace(); } finally { try { if(br!=null){ br.close(); br=null; } if(isr!=null){ isr.close(); isr=null; } if(fis!=null){ fis.close(); fis=null; } } catch (Exception e) { e.printStackTrace(); } } return html; } //任意html,殘缺不全也可以 public String parseHtml(String html) { /* * <.*?>爲正則表達式,其中的.表示任意字符,*?表示出現0次或0次以上,此方法可以去掉雙頭標籤(雙頭針對於殘缺的標籤) * "<.*?"表示<尖括號後的所有字符,此方法可以去掉殘缺的標籤,及後面的內容 * "",若有多種此種字符,可用同一方法去除 */ html = html.replaceAll("<.*?>", " ").replaceAll("", " "); html = html.replaceAll("<.*?", ""); return (html + "..."); } //可以指定截取長度 public String parseHtml(String html,int length) { if(html.length()<length){ return "截取長度超過文件內容總長"; } return parseHtml(html.substring(0, length)); } }

發佈了26 篇原創文章 · 獲贊 34 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章