一個(gè)mybatis分頁(yè)工具類

1.PagePlugin類

package com.tyro.plugin;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import com.tyro.util.ReflectHelper;
import com.tyro.util.Tools;
/**
 * 
* 類名稱:PagePlugin.java
* 類描述: 
* @author fuhang
* 作者單位: 
* 聯(lián)系方式:
* 創(chuàng)建時(shí)間:2014年7月1日
* @version 1.0
 */
@Intercepts({@Signature(type=StatementHandler.class,method="prepare",args={Connection.class})})
public class PagePlugin implements Interceptor {

    private static String dialect = ""; //數(shù)據(jù)庫(kù)方言
    private static String pageSqlId = ""; //mapper.xml中需要攔截的ID(正則匹配)
    
    public Object intercept(Invocation ivk) throws Throwable {
        if(ivk.getTarget() instanceof RoutingStatementHandler){
            RoutingStatementHandler statementHandler = (RoutingStatementHandler)ivk.getTarget();
            BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
            MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, "mappedStatement");
            
            if(mappedStatement.getId().matches(pageSqlId)){ //攔截需要分頁(yè)的SQL
                BoundSql boundSql = delegate.getBoundSql();
                Object parameterObject = boundSql.getParameterObject();//分頁(yè)SQL<select>中parameterType屬性對(duì)應(yīng)的實(shí)體參數(shù)小腊,即Mapper接口中執(zhí)行分頁(yè)方法的參數(shù),該參數(shù)不得為空
                if(parameterObject==null){
                    throw new NullPointerException("parameterObject尚未實(shí)例化!");
                }else{
                    Connection connection = (Connection) ivk.getArgs()[0];
                    String sql = boundSql.getSql();
                    //String countSql = "select count(0) from (" + sql+ ") as tmp_count"; //記錄統(tǒng)計(jì)
                    String countSql = "select count(0) from (" + sql+ ")  tmp_count"; //記錄統(tǒng)計(jì) == oracle 加 as 報(bào)錯(cuò)(SQL command not properly ended)
                    PreparedStatement countStmt = connection.prepareStatement(countSql);
                    BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(),countSql,boundSql.getParameterMappings(),parameterObject);
                    setParameters(countStmt,mappedStatement,countBS,parameterObject);
                    ResultSet rs = countStmt.executeQuery();
                    int count = 0;
                    if (rs.next()) {
                        count = rs.getInt(1);
                    }
                    rs.close();
                    countStmt.close();
                    //System.out.println(count);
                    Page page = null;
                    if(parameterObject instanceof Page){    //參數(shù)就是Page實(shí)體
                         page = (Page) parameterObject;
                         page.setEntityOrField(true);    
                        page.setTotalResult(count);
                    }else{  //參數(shù)為某個(gè)實(shí)體久窟,該實(shí)體擁有Page屬性
                        Field pageField = ReflectHelper.getFieldByFieldName(parameterObject,"page");
                        if(pageField!=null){
                            page = (Page) ReflectHelper.getValueByFieldName(parameterObject,"page");
                            if(page==null)
                                page = new Page();
                            page.setEntityOrField(false); 
                            page.setTotalResult(count);
                            ReflectHelper.setValueByFieldName(parameterObject,"page", page); //通過(guò)反射秩冈,對(duì)實(shí)體對(duì)象設(shè)置分頁(yè)對(duì)象
                        }else{
                            throw new NoSuchFieldException(parameterObject.getClass().getName()+"不存在 page 屬性!");
                        }
                    }
                    String pageSql = generatePageSql(sql,page);
                    ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql); //將分頁(yè)sql語(yǔ)句反射回BoundSql.
                }
            }
        }
        return ivk.proceed();
    }

    
    /**
     * 對(duì)SQL參數(shù)(?)設(shè)值,參考o(jì)rg.apache.ibatis.executor.parameter.DefaultParameterHandler
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if (value != null) {
                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                        }
                    } else {
                        value = metaObject == null ? null : metaObject.getValue(propertyName);
                    }
                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
                }
            }
        }
    }
    
    /**
     * 根據(jù)數(shù)據(jù)庫(kù)方言斥扛,生成特定的分頁(yè)sql
     * @param sql
     * @param page
     * @return
     */
    private String generatePageSql(String sql,Page page){
        if(page!=null && Tools.notEmpty(dialect)){
            StringBuffer pageSql = new StringBuffer();
            if("mysql".equals(dialect)){
                pageSql.append(sql);
                pageSql.append(" limit "+page.getCurrentResult()+","+page.getShowCount());
            }else if("oracle".equals(dialect)){
                pageSql.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
                pageSql.append(sql);
                //pageSql.append(") as tmp_tb where ROWNUM<=");
                pageSql.append(") tmp_tb where ROWNUM<=");
                pageSql.append(page.getCurrentResult()+page.getShowCount());
                pageSql.append(") where row_id>");
                pageSql.append(page.getCurrentResult());
            }
            return pageSql.toString();
        }else{
            return sql;
        }
    }
    
    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }

    public void setProperties(Properties p) {
        dialect = p.getProperty("dialect");
        if (Tools.isEmpty(dialect)) {
            try {
                throw new PropertyException("dialect property is not found!");
            } catch (PropertyException e) {
                e.printStackTrace();
            }
        }
        pageSqlId = p.getProperty("pageSqlId");
        if (Tools.isEmpty(pageSqlId)) {
            try {
                throw new PropertyException("pageSqlId property is not found!");
            } catch (PropertyException e) {
                e.printStackTrace();
            }
        }
    }
    
}

2.Page類

package com.tyro.plugin;

import com.tyro.util.Const;
import com.tyro.util.ParameterMap;
import com.tyro.util.Tools;

public class Page {
    
    private int showCount; //每頁(yè)顯示記錄數(shù)
    private int totalPage;      //總頁(yè)數(shù)
    private int totalResult;    //總記錄數(shù)
    private int currentPage;    //當(dāng)前頁(yè)
    private int currentResult;  //當(dāng)前記錄起始索引
    private boolean entityOrField;  //true:需要分頁(yè)的地方入问,傳入的參數(shù)就是Page實(shí)體;false:需要分頁(yè)的地方稀颁,傳入的參數(shù)所代表的實(shí)體擁有Page屬性
    private String pageStr;     //最終頁(yè)面顯示的底部翻頁(yè)導(dǎo)航芬失,詳細(xì)見(jiàn):getPageStr();
    private ParameterMap pd = new ParameterMap();
    

    
    public Page(){
        try {
            this.showCount = Integer.parseInt(Tools.readTxtFile(Const.PAGE));
        } catch (Exception e) {
            this.showCount = 15;
        }
    }
    
    public int getTotalPage() {
        if(totalResult%showCount==0)
            totalPage = totalResult/showCount;
        else
            totalPage = totalResult/showCount+1;
        return totalPage;
    }
    
    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }
    
    public int getTotalResult() {
        return totalResult;
    }
    
    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }
    
    public int getCurrentPage() {
        if(currentPage<=0)
            currentPage = 1;
        return currentPage;
    }
    
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    
    public String getPageStr() {
        StringBuffer sb = new StringBuffer();
        if(totalResult>0){
            sb.append(" <ul>\n");
            if(currentPage==1){
                sb.append(" <li><a>共<font color=red>"+totalResult+"</font>條</a></li>\n");
                sb.append(" <li><input type=\"number\" value=\"\" id=\"toGoPage\" style=\"width:50px;text-align:center;float:left\" placeholder=\"頁(yè)碼\"/></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"toTZ();\"  class=\"btn btn-mini btn-success\">跳轉(zhuǎn)</a></li>\n");
                sb.append(" <li><a>首頁(yè)</a></li>\n");
                sb.append(" <li><a>上頁(yè)</a></li>\n");
            }else{
                sb.append(" <li><a>共<font color=red>"+totalResult+"</font>條</a></li>\n");
                sb.append(" <li><input type=\"number\" value=\"\" id=\"toGoPage\" style=\"width:50px;text-align:center;float:left\" placeholder=\"頁(yè)碼\"/></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"toTZ();\"  class=\"btn btn-mini btn-success\">跳轉(zhuǎn)</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage(1)\">首頁(yè)</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("+(currentPage-1)+")\">上頁(yè)</a></li>\n");
            }
            int showTag = 5;//分頁(yè)標(biāo)簽顯示數(shù)量
            int startTag = 1;
            if(currentPage>showTag){
                startTag = currentPage-1;
            }
            int endTag = startTag+showTag-1;
            for(int i=startTag; i<=totalPage && i<=endTag; i++){
                if(currentPage==i)
                    sb.append("<li><a><font color='#808080'>"+i+"</font></a></li>\n");
                else
                    sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("+i+")\">"+i+"</a></li>\n");
            }
            if(currentPage==totalPage){
                sb.append(" <li><a>下頁(yè)</a></li>\n");
                sb.append(" <li><a>尾頁(yè)</a></li>\n");
            }else{
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("+(currentPage+1)+")\">下頁(yè)</a></li>\n");
                sb.append(" <li style=\"cursor:pointer;\"><a onclick=\"nextPage("+totalPage+")\">尾頁(yè)</a></li>\n");
            }
            sb.append(" <li><a>第"+currentPage+"頁(yè)</a></li>\n");
            sb.append(" <li><a>共"+totalPage+"頁(yè)</a></li>\n");
            
            
            sb.append(" <li><select title='顯示條數(shù)' style=\"width:55px;float:left;\" onchange=\"changeCount(this.value)\">\n");
            sb.append(" <option value='"+showCount+"'>"+showCount+"</option>\n");
            sb.append(" <option value='10'>10</option>\n");
            sb.append(" <option value='20'>20</option>\n");
            sb.append(" <option value='30'>30</option>\n");
            sb.append(" <option value='40'>40</option>\n");
            sb.append(" <option value='50'>50</option>\n");
            sb.append(" <option value='60'>60</option>\n");
            sb.append(" <option value='70'>70</option>\n");
            sb.append(" <option value='80'>80</option>\n");
            sb.append(" <option value='90'>90</option>\n");
            sb.append(" <option value='99'>99</option>\n");
            sb.append(" </select>\n");
            sb.append(" </li>\n");
            
            
            
            sb.append("</ul>\n");
            sb.append("<script type=\"text/javascript\">\n");
            
            //換頁(yè)函數(shù)
            sb.append("function nextPage(page){");
            sb.append(" top.jzts();");
            sb.append(" if(true && document.forms[0]){\n");
            sb.append("     var url = document.forms[0].getAttribute(\"action\");\n");
            sb.append("     if(url.indexOf('?')>-1){url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     url = url + page + \"&" +(entityOrField?"showCount":"page.showCount")+"="+showCount+"\";\n");
            sb.append("     document.forms[0].action = url;\n");
            sb.append("     document.forms[0].submit();\n");
            sb.append(" }else{\n");
            sb.append("     var url = document.location+'';\n");
            sb.append("     if(url.indexOf('?')>-1){\n");
            sb.append("         if(url.indexOf('currentPage')>-1){\n");
            sb.append("             var reg = /currentPage=\\d*/g;\n");
            sb.append("             url = url.replace(reg,'currentPage=');\n");
            sb.append("         }else{\n");
            sb.append("             url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";\n");
            sb.append("         }\n");
            sb.append("     }else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     url = url + page + \"&" +(entityOrField?"showCount":"page.showCount")+"="+showCount+"\";\n");
            sb.append("     document.location = url;\n");
            sb.append(" }\n");
            sb.append("}\n");
            
            //調(diào)整每頁(yè)顯示條數(shù)
            sb.append("function changeCount(value){");
            sb.append(" top.jzts();");
            sb.append(" if(true && document.forms[0]){\n");
            sb.append("     var url = document.forms[0].getAttribute(\"action\");\n");
            sb.append("     if(url.indexOf('?')>-1){url += \"&"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     url = url + \"1&" +(entityOrField?"showCount":"page.showCount")+"=\"+value;\n");
            sb.append("     document.forms[0].action = url;\n");
            sb.append("     document.forms[0].submit();\n");
            sb.append(" }else{\n");
            sb.append("     var url = document.location+'';\n");
            sb.append("     if(url.indexOf('?')>-1){\n");
            sb.append("         if(url.indexOf('currentPage')>-1){\n");
            sb.append("             var reg = /currentPage=\\d*/g;\n");
            sb.append("             url = url.replace(reg,'currentPage=');\n");
            sb.append("         }else{\n");
            sb.append("             url += \"1&"+(entityOrField?"currentPage":"page.currentPage")+"=\";\n");
            sb.append("         }\n");
            sb.append("     }else{url += \"?"+(entityOrField?"currentPage":"page.currentPage")+"=\";}\n");
            sb.append("     url = url + \"&" +(entityOrField?"showCount":"page.showCount")+"=\"+value;\n");
            sb.append("     document.location = url;\n");
            sb.append(" }\n");
            sb.append("}\n");
            
            //跳轉(zhuǎn)函數(shù) 
            sb.append("function toTZ(){");
            sb.append("var toPaggeVlue = document.getElementById(\"toGoPage\").value;");
            sb.append("if(toPaggeVlue == ''){document.getElementById(\"toGoPage\").value=1;return;}");
            sb.append("if(isNaN(Number(toPaggeVlue))){document.getElementById(\"toGoPage\").value=1;return;}");
            sb.append("nextPage(toPaggeVlue);");
            sb.append("}\n");
            sb.append("</script>\n");
        }
        pageStr = sb.toString();
        return pageStr;
    }
    
    public void setPageStr(String pageStr) {
        this.pageStr = pageStr;
    }
    
    public int getShowCount() {
        return showCount;
    }
    
    public void setShowCount(int showCount) {
        
        this.showCount = showCount;
    }
    
    public int getCurrentResult() {
        currentResult = (getCurrentPage()-1)*getShowCount();
        if(currentResult<0)
            currentResult = 0;
        return currentResult;
    }
    
    public void setCurrentResult(int currentResult) {
        this.currentResult = currentResult;
    }
    
    public boolean isEntityOrField() {
        return entityOrField;
    }
    
    public void setEntityOrField(boolean entityOrField) {
        this.entityOrField = entityOrField;
    }
    
    public ParameterMap getPm() {
        return pd;
    }

    public void setPm(ParameterMap pd) {
        this.pd = pd;
    }
    
}

3.ReflectHelper類

package com.tyro.util;

import java.lang.reflect.Field;

/**
 * @author Administrator
 *  反射工具
 *  分頁(yè)獲取到
 */
public class ReflectHelper {
    /**
     * 獲取obj對(duì)象fieldName的Field
     * @param obj
     * @param fieldName
     * @return
     */
    public static Field getFieldByFieldName(Object obj, String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }

    /**
     * 獲取obj對(duì)象fieldName的屬性值
     * @param obj
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Object getValueByFieldName(Object obj, String fieldName)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        Object value = null;
        if(field!=null){
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
        return value;
    }

    /**
     * 設(shè)置obj對(duì)象fieldName的屬性值
     * @param obj
     * @param fieldName
     * @param value
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void setValueByFieldName(Object obj, String fieldName,
            Object value) throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}

4.Tool類

package com.tyro.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {
    
    /**
     * 隨機(jī)生成六位數(shù)驗(yàn)證碼 
     * @return
     */
    public static int getRandomNum(){
         Random r = new Random();
         return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
    }
    
    /**
     * 檢測(cè)字符串是否不為空(null,"","null")
     * @param s
     * @return 不為空則返回true,否則返回false
     */
    public static boolean notEmpty(String s){
        return s!=null && !"".equals(s) && !"null".equals(s);
    }
    
    /**
     * 檢測(cè)字符串是否為空(null,"","null")
     * @param s
     * @return 為空則返回true峻村,不否則返回false
     */
    public static boolean isEmpty(String s){
        return s==null || "".equals(s) || "null".equals(s);
    }
    

    /**
     * 寫(xiě)txt里的單行內(nèi)容
     * @param filePath  文件路徑
     * @param content  寫(xiě)入的內(nèi)容
     */
    public static void writeFile(String fileP,String content){
        String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";  //項(xiàng)目路徑
        filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
        if(filePath.indexOf(":") != 1){
            filePath = File.separator + filePath;
        }
        try {
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");      
            BufferedWriter writer=new BufferedWriter(write);          
            writer.write(content);      
            writer.close(); 

            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
      * 驗(yàn)證郵箱
      * @param email
      * @return
      */
     public static boolean checkEmail(String email){
      boolean flag = false;
      try{
        String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        flag = matcher.matches();
       }catch(Exception e){
        flag = false;
       }
      return flag;
     }
    
     /**
      * 驗(yàn)證手機(jī)號(hào)碼
      * @param mobiles
      * @return
      */
     public static boolean checkMobileNumber(String mobileNumber){
      boolean flag = false;
      try{
        Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
        Matcher matcher = regex.matcher(mobileNumber);
        flag = matcher.matches();
       }catch(Exception e){
        flag = false;
       }
      return flag;
     }
     
     
    /**
     * 讀取txt里的單行內(nèi)容
     * @param filePath  文件路徑
     */
    public static String readTxtFile(String fileP) {
        try {
            
//          String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../";  //項(xiàng)目路徑
            String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""));   //項(xiàng)目路徑
            filePath = filePath.replaceAll("file:/", "");
            filePath = filePath.replaceAll("%20", " ");
            filePath = filePath.trim() + fileP.trim();
            if(filePath.indexOf(":") != 1){
                filePath = File.separator + filePath;
            }
            String encoding = "utf-8";
            System.out.println("filePath:"+filePath);
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {       // 判斷文件是否存在
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file), encoding);   // 考慮到編碼格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    return lineTxt;
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件,查看此路徑是否正確:"+filePath);
            }
        } catch (Exception e) {
            System.out.println("讀取文件內(nèi)容出錯(cuò)");
        }
        return "";
    }
    
}

留著筆記麸折,碼農(nóng)專用。粘昨。。窜锯。张肾。。锚扎。吞瞪。。驾孔。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末芍秆,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子翠勉,更是在濱河造成了極大的恐慌妖啥,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,482評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件对碌,死亡現(xiàn)場(chǎng)離奇詭異荆虱,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)怀读,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)诉位,“玉大人,你說(shuō)我怎么就攤上這事菜枷〔钥罚” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,762評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵啤誊,是天一觀的道長(zhǎng)椿息。 經(jīng)常有香客問(wèn)我,道長(zhǎng)坷衍,這世上最難降的妖魔是什么寝优? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,273評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮枫耳,結(jié)果婚禮上乏矾,老公的妹妹穿的比我還像新娘。我一直安慰自己迁杨,他們只是感情好钻心,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,289評(píng)論 5 373
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著铅协,像睡著了一般捷沸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上狐史,一...
    開(kāi)封第一講書(shū)人閱讀 49,046評(píng)論 1 285
  • 那天痒给,我揣著相機(jī)與錄音,去河邊找鬼骏全。 笑死苍柏,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的姜贡。 我是一名探鬼主播试吁,決...
    沈念sama閱讀 38,351評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼楼咳!你這毒婦竟也來(lái)了熄捍?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,988評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤母怜,失蹤者是張志新(化名)和其女友劉穎余耽,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體糙申,經(jīng)...
    沈念sama閱讀 43,476評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡宾添,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,948評(píng)論 2 324
  • 正文 我和宋清朗相戀三年船惨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缕陕。...
    茶點(diǎn)故事閱讀 38,064評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡粱锐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出扛邑,到底是詐尸還是另有隱情怜浅,我是刑警寧澤,帶...
    沈念sama閱讀 33,712評(píng)論 4 323
  • 正文 年R本政府宣布蔬崩,位于F島的核電站恶座,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏沥阳。R本人自食惡果不足惜跨琳,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,261評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望桐罕。 院中可真熱鬧脉让,春花似錦、人聲如沸功炮。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,264評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)薪伏。三九已至滚澜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間嫁怀,已是汗流浹背设捐。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,486評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留眶掌,地道東北人挡育。 一個(gè)月前我還...
    沈念sama閱讀 45,511評(píng)論 2 354
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像朴爬,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子橡淆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,802評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容

  • @font-face{ font-family:"Times New Roman"; } @font-face{ ...
    niki閱讀 434評(píng)論 0 1
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法召噩,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法逸爵,繼承相關(guān)的語(yǔ)法具滴,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,581評(píng)論 18 399
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,510評(píng)論 25 707
  • 鶴望蘭花語(yǔ)~自由的追夢(mèng)人师倔。夕陽(yáng)西下构韵,一畫(huà)一世界,每日一畫(huà),和筆尖的約會(huì)疲恢。 昨天在簡(jiǎn)書(shū)一個(gè)全職媽媽那看見(jiàn)的畫(huà)凶朗,于是依...
    蛋糕小姐閱讀 484評(píng)論 0 2
  • 一個(gè)痛恨男人的女人 找到真愛(ài)的男人 一個(gè)追求利益的男人 放下一切歸隱 一個(gè)愛(ài)情至上的女人夢(mèng)想破碎 一個(gè)占有的人 獻(xiàn)...
    helen1990_閱讀 398評(píng)論 0 0