【Java.Regex】用正則表達式查找Java源文件中的註釋

代碼:

package regex;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindCommentsInJavaFile {
     public static void main(String[] args) {
            // Get content from a txt file,there are several methods to do that
            StringBuilder sb=new StringBuilder();
            try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("D:\\logs\\ThreadInserter.java"));){
                String line = null;

                while ((line = lineNumberReader.readLine()) != null) {
                    sb.append(line+"\n");// \n is necessary
                }
            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } 
            String content=sb.toString();
            
            // (//[^\n]*):雙斜槓註釋
            // ((/[*]([*@]|[\n]|\\w|\\d|\\s|[^\\x00-\\xff])+[*]/)):斜槓星註釋
            // /[*]:Start /*
            // [*@]:allow * @
            // [\n]:allow new line
            // \\w|\\d|\\s:allow word,digit,space
            // [^\\x00-\\xff]:allow double bytes characters
            // +:([*@]|[\n]|\\w|\\d|\\s|[^\\x00-\\xff]) repeat at least once
            // [*]/:end */
            java.util.regex.Pattern pattern=Pattern.compile("(//[^\n]*)|((/[*]([*@]|[\n]|\\w|\\d|\\s|[^\\x00-\\xff])+[*]/))");
            Matcher matcher=pattern.matcher(content);
            boolean isfindTarget=matcher.find();
            
            while(isfindTarget) {
                if(matcher.group(1)!=null) {
                    System.out.println("雙斜槓註釋:" + ":" + matcher.group(1)+"\n");
                }else if(matcher.group(2)!=null) {
                    System.out.println("斜槓星註釋:" + ":" + matcher.group(2)+"\n");
                }
                
                isfindTarget=matcher.find();
            }
        }
}

輸出:

斜槓星註釋::/**
 * Used a thread to insert records to a table
 *
 */

雙斜槓註釋::// Table's serial number

雙斜槓註釋::// Tbale's name

雙斜槓註釋::// how many records should be inserted

雙斜槓註釋::// array contains table types/fields

雙斜槓註釋::// Connection used in single thread

雙斜槓註釋::// statemenet used in single throead

雙斜槓註釋::// How many times this thread should run

雙斜槓註釋::// Reference to manager

斜槓星註釋::/**
     * Constructor
     * @param tbSN
     * @param tableName
     * @param count
     * @param innerArr
     */

斜槓星註釋::/**
     * thread method
     */

雙斜槓註釋::// Initialize conn/stmt

雙斜槓註釋::// Clear

雙斜槓註釋::// Insert

雙斜槓註釋::///

斜槓星註釋::/**
            * 清空一個表的數據,注意此功能有破壞性,不可恢復,注意備份好數據
     * @param tableName
     * @param conn
     * @param stmt
     * @throws SQLException
     */

斜槓星註釋::/**
            * 向一個表插入數據
     * @param tableName
     * @param count
     * @param innerArr
     * @param conn
     * @param stmt
     * @throws SQLException
     */

雙斜槓註釋::// 得到字段名和字段類型

雙斜槓註釋::// 兩年的秒數除以總個數即爲間隔

雙斜槓註釋:://int times=count/BatchSize;

斜槓星註釋::/**
            * 得到批量插入語句
     * @param tableName
     * @param typefields
     * @param index
     * @return
     */

雙斜槓註釋:://values.add("'"+String.valueOf(index)+"'");

斜槓星註釋::/**
     * 以當前時間爲基準減去數十秒
     * @param n
     * @return
     */

雙斜槓註釋:://日期減去n*10秒

斜槓星註釋::/*3432432432432*/

斜槓星註釋::/**
     * 將秒轉化爲日時分秒
     * @param secondCount
     * @return
     */

當作目標文件的Java源文件:

package test.threadinsert;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * Used a thread to insert records to a table
 *
 */
public class ThreadInserter extends Thread{
    private static Logger log = Logger.getLogger(ThreadInserter.class);
    
    private static final int BatchSize=500;
    private int tbSN;            // Table's serial number
    private String tableName;    // Tbale's name
    private int count;            // how many records should be inserted
    private String[] innerArr;  // array contains table types/fields
    private Connection conn;    // Connection used in single thread
    private Statement stmt;        // statemenet used in single throead
    private int times;            // How many times this thread should run
    private InserterManager manager;// Reference to manager
    
    /**
     * Constructor
     * @param tbSN
     * @param tableName
     * @param count
     * @param innerArr
     */
    public ThreadInserter(int tbSN,String tableName,int count,String[] innerArr,InserterManager manager) {
        this.tbSN=tbSN;
        this.tableName=tableName;
        this.count=count;
        this.innerArr=innerArr;
        this.times=count/BatchSize;
        this.manager=manager;
    }
    
    /**
     * thread method
     */
    public void run() {
        try {
            log.info("Start...");
            long startTime = System.currentTimeMillis();
            
            // Initialize conn/stmt
            DbParam_Dev dbParam=new DbParam_Dev();
            Class.forName(dbParam.Driver).newInstance();
            conn = DriverManager.getConnection(dbParam.DbUrl, dbParam.User, dbParam.Pswd);
            stmt = conn.createStatement();
            
            // Clear
            truncateTable();
            // Insert
            insertTestDataTo();
            
            long endTime = System.currentTimeMillis();
            String timeElasped=sec2DHMS((endTime - startTime)/1000);
            log.info("#"+tbSN+" End. "+count+" records have been inserted to '"+tableName+"'.( time elapsed: " + timeElasped +")");
            
            ///
            manager.reportFinished(String.valueOf(tbSN), tableName, timeElasped);
        }catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                System.out.print("Can't close stmt/conn because of " + e.getMessage());
            }
        }
    }
    
     /**
            * 清空一個表的數據,注意此功能有破壞性,不可恢復,注意備份好數據
     * @param tableName
     * @param conn
     * @param stmt
     * @throws SQLException
     */
    private void truncateTable() throws SQLException{
        String sql="truncate table "+tableName;
        stmt.execute(sql);
        log.info("truncated table:"+tableName);
    }
    
    /**
            * 向一個表插入數據
     * @param tableName
     * @param count
     * @param innerArr
     * @param conn
     * @param stmt
     * @throws SQLException
     */
    private void insertTestDataTo() throws SQLException{
        // 得到字段名和字段類型
        List<TypeField> typefields=new ArrayList<TypeField>();
        for(int i=1;i<innerArr.length;i++) {
            String temp=innerArr[i];
            String[] arrTmp=temp.split(":");
            
            TypeField tf=new TypeField();
            tf.type=arrTmp[0];
            tf.field=arrTmp[1];
            typefields.add(tf);
        }
        
        List<String> fields=new ArrayList<String>();
        List<String> values=new ArrayList<String>();
        int index=0;
        for(TypeField tf:typefields) {
            fields.add(tf.field);
            values.add("''{"+index+"}''");
            index++;
        }
        
        int interval=2*365*24*60*60/count;// 兩年的秒數除以總個數即爲間隔
        
        index=0;
        //int times=count/BatchSize;
        for(int i=0;i<this.times;i++) {
            StringBuilder sb=new StringBuilder();
            sb.append("INSERT ALL ");
            
            for(int j=0;j<BatchSize;j++) {
                index=i*BatchSize+j;
                sb.append(getInsertSql(tableName,typefields,index,interval));
            }
            
            sb.append(" select * from dual");
            String sql = sb.toString();
            
            long startTime = System.currentTimeMillis();
            stmt.executeUpdate(sql);
            long endTime = System.currentTimeMillis();
            log.info("#"+tbSN+"-("+i+"/"+this.times+") "+BatchSize+" records inserted to '"+tableName+"' used " + sec2DHMS((endTime - startTime)/1000));
        }
    }
    
    /**
            * 得到批量插入語句
     * @param tableName
     * @param typefields
     * @param index
     * @return
     */
    private String getInsertSql(String tableName,List<TypeField> typefields,int index,int interval) {
        String currTime=getDatetimeBefore(index,interval);
        
        StringBuilder sb=new StringBuilder();
        sb.append(" INTO "+tableName+"(");
        List<String> fields=new ArrayList<String>();
        for(TypeField tf:typefields) {
            fields.add(tf.field);
        }
        sb.append(String.join(",",fields));
        
        sb.append(") values(");
        List<String> values=new ArrayList<String>();
        for(TypeField tf:typefields) {
            if(tf.type.equals("PK")) {
                //values.add("'"+String.valueOf(index)+"'");
                
                if(tableName.contains("DELIVERY_INFO_HISTORY")) {
                    values.add("'0'");
                }else {
                    values.add("'"+String.valueOf(index)+"'");
                }
            }else if(tf.type.equals("CH")) {
                values.add("'0'");
            }else if(tf.type.equals("US")) {
                values.add("'unknown'");
            }else if(tf.type.equals("DT")) {
                values.add("to_date('"+currTime+"','yyyy-MM-dd HH24:mi:ss')");
            }
        }
        sb.append(String.join(",",values));
        sb.append(")");
        
        String insertSql=sb.toString();
        return insertSql;
    }
    
    /**
     * 以當前時間爲基準減去數十秒
     * @param n
     * @return
     */
    private static String getDatetimeBefore(int n,int interval) {
        try {
            Calendar now = Calendar.getInstance();
            
            now.add(Calendar.SECOND,-n*interval);//日期減去n*10秒
            
            Date newDate=now.getTime();/*3432432432432*/
            
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String retval = sdf.format(newDate);
            return retval;
        }
        catch(Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    
    /**
     * 將秒轉化爲日時分秒
     * @param secondCount
     * @return
     */
    private static String sec2DHMS(long secondCount) {
        String retval = null;
    
        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;
        
        String strSeconds="";
        if(seconds!=0) {
            strSeconds=seconds + "s";
        }
    
        if (days > 0) {
            retval = days + "d" + hours + "h" + minutes + "m" + strSeconds;
        } else if (hours > 0) {
            retval = hours + "h" + minutes + "m" + strSeconds;
        } else if (minutes > 0) {
            retval = minutes + "m" + strSeconds;
        } else {
            retval = strSeconds;
        }
        
        
        String str="AAA";
        str="\"";
        str="";
        str="";
        str="";
    
        return retval;
    }
}

--END-- 2019-11-20 10:15

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章