代码:

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;

/**
 * 查找一个Java源文件中的成员函数名
 *
 */
public class FindFunctionNames {
    public static void main(String[] args) {
        // (\\w+):group(1) 匹配public/protected/private
        // (\\s+):group(2) 匹配一个或多个空格
        // (\\w+):group(3) 匹配返回值如void,String
        // (\\s+):group(4) 匹配一个或多个空格
        // ([_a-zA-Z]+[_a-zA-Z0-9]*):group(5) 匹配函数名
        // ([(]([^()]*)[)]):group(1) 匹配函数的参数
        java.util.regex.Pattern pattern=Pattern.compile("(\\s+)(\\w+)(\\s+)(\\w+)(\\s+)([_a-zA-Z]+[_a-zA-Z0-9]*)([(]([^()]*)[)])");

        try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("D:\\logs\\AllocationRequestFileToDbJob.java"));){
            String line = null;

            while ((line = lineNumberReader.readLine()) != null) {
                Matcher matcher=pattern.matcher(line);
                while(matcher.find()) {
                    System.out.println("Line " + lineNumberReader.getLineNumber() +":" + matcher.group(6)+ matcher.group(7));
                }
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

输出:

Line 52:run() {
Line 93:truncateTable() throws SQLException{
Line 108:insertTestDataTo() throws SQLException{
Line 160:getInsertSql(String tableName,List<TypeField> typefields,int index,int interval) {
Line 202:getDatetimeBefore(int n,int interval) {
Line 225:sec2DHMS(long secondCount) {

源文件:

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("'heyang'");
            }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();

            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;
        }

        return retval;
    }
}

--END-- 14:27

【Java.Regex】使用正则表达式查找一个Java类中的成员函数的更多相关文章

  1. C++(十六) — 类中引用成员函数、命名空间的使用

    1.为什么类中引用成员函数? 类将属性和方法做了封装.类是一种数据类型,也就是:固定大小内存块的别名. 类的定义是一个抽象的概念,定义时不分配内存,当用类定义对象时,才分配一个固定大小的内存块. 此时 ...

  2. 对类中的成员函数的定义和声明最后添加一个const是什么意思?

    1.const修饰的成员函数只能调用const修饰的成员函数,且不能修改数据成员变量的值. 2.const修饰的类对象只能调用const修饰的成员函数. 3.const修饰的类对象可以调用非const ...

  3. C++类中的成员函数和构造函数为模板函数时的调用方法

    所谓模板函数其实就是建立一个通用函数,这个通用函数的形参类型不具体指定,用一个虚拟类型来代表,这个通用函数就被称为函数模板. 例: #include <iostream> using na ...

  4. c++ 类中模版成员函数

    C++函数模版与类模版. template <class T> void SwapFunction(T &first, T &second){ }//函数模版 templa ...

  5. C++类的成员函数(在类外定义成员函数、inline成员函数)

    类的成员函数(简称类函数)是函数的一种,它的用法和作用和前面介绍过的函数基本上是一样的,它也有返回值和函数类型,它与一般函数的区别只是:它是属于一个类的成员,出现在类体中.它可以被指定为private ...

  6. C++:类中的赋值函数

    先来看一个例子: #include<iostream> #include<string> using namespace std; class Student{ public: ...

  7. Java基础-继承-编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数 loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个 类都有构造方法和输出相关数据的方法。最后,写一个测试类来测试这些类的功 能。

    #29.编写一个Java应用程序,设计一个汽车类Vehicle,包含的属性有车轮个数 wheels和车重weight.小车类Car是Vehicle的子类,其中包含的属性有载人数 loader.卡车类T ...

  8. “全栈2019”Java第七十九章:类中可以嵌套接口吗?

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  9. c语言经典算法——查找一个整数数组中第二大数

    题目: 实现一个函数,查找一个整数数组中第二大数. 算法思想: 设置两个变量max1和max2,用来保存最大数和第二大数,然后将数组剩余的数依次与这两个数比较,如果这个数a比max1大,则先将max1 ...

随机推荐

  1. error 106: Can't Access ASP.NET\ClientFiles\

    Error 1606 Can’t access ASP.NET\ClientFiles\ when installing Crystal Reports Support Pack 10     Sea ...

  2. Linux命令——tree

    参考:Linux tree Command Tutorial for Beginners (6 Examples) 简介 Linux tree命令用于以树状图列出目录的内容. 执行tree指令,它会列 ...

  3. MySQL查询(关联查询)

    一.mysql查询与权限 (一)数据库关联查询 **内连接查询(inner join)** 查询两个表共有的数据,交集 SELECT * FROM tb1 INNER JOIN tb2 ON 条件 所 ...

  4. java操作redis(jedis)常用方法示例

    说明:redis命令和jedis方法名基本是一一对应的 Redis常用命令1 连接操作命令 ● quit:关闭连接(connection) ● auth:简单密码认证 ● help cmd: 查看cm ...

  5. mysqlslap压测

    mysqlslap 是MySQL自带的压测工具: -P --create-schema=test -S /tmp/mysql_sandbox18601.sock --number-of-queries ...

  6. linux 下安装node 并使用nginx做域名绑定

    #1 ,home目录下 下载nodejs安装包,解压 并修改文件夹名称 wget https://nodejs.org/dist/v8.11.4/node-v8.11.4-linux-x64.tar. ...

  7. keras模块学习之-参数初始化与对象调用-笔记

    本笔记由博客园-圆柱模板 博主整理笔记发布,转载需注明,谢谢合作! 参数初始化(Initializations) 这个模块的作用是在添加layer时调用init进行这一层的权重初始化,有两种初始化方法 ...

  8. HP DL388 Gen9 Raid P440ar 工具

    HP DL388 Gen9 服务器raid升级P440ar,原先的hpacucli 不能使用,新的工具为hpssacl hpssacli-2.10-14.0.x86_64.rpm 下载地址:wget ...

  9. C# 3.0 扩展方法&接口

    namespace ExtensionInterfaceMethod { class Program { static void Main(string[] args) { //使用接口变量来调用扩展 ...

  10. Validation参数验证

    在SpringBoot项目中其实已经默认引入了,如果不是sprongBoot项目则需要导入Maven <dependency> <groupId>org.hibernate.v ...