代码:

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文件里的字符串
 * @author 逆火
 *
 * 2019年11月19日 下午9:12:59
 */
public class FindStringInJavaFile {
    public static void main(String[] args) {
        // 最外层(.....):group(1)
        // \":匹配字符串开始的双引号,单个\为转义
        // 内层(...)*:前后引号中间的文本,*为括号中的模式重复0-n次
        // \\\\\":匹配\"
        // \\\\\\\\:匹配\\
        // \\\\n:匹配\n
        // [^\"]:除了双引号之外的字符
        // \":匹配字符串结束开始的双引号,单个\为转义        // 注意:对于通常运用,可能 java.util.regex.Pattern pattern=Pattern.compile("(\"(\\\\\"|[^\"])*\")"); 就足够了。        java.util.regex.Pattern pattern=Pattern.compile("(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")");

        try (LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("D:\\logs\\InsertThread.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(0));
                }
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

输出:

Line 63:"Begin to access "
Line 63:" as "
Line 63:"..."
Line 71:"#"
Line 71:" "
Line 71:" records were inserted to table:'"
Line 71:"' used "
Line 83:"Can't close stmt/conn because of "
Line 97:"SELECT COUNT (*) as cnt FROM "
Line 102:"cnt"
Line 123:"yyyy-MM-dd HH:mm:ss"
Line 141:"truncate table "
Line 143:"truncated table:"
Line 161:":"
Line 174:"''{"
Line 174:"}''"
Line 184:"INSERT ALL "
Line 191:" select * from dual"
Line 197:"#"
Line 197:"-"
Line 197:" "
Line 197:" records inserted to '"
Line 197:"' used "
Line 212:" INTO "
Line 212:"("
Line 217:","
Line 219:") values("
Line 222:"PK"
Line 223:"'"
Line 223:"'"
Line 225:"DELIVERY_INFO_HISTORY"
Line 226:"'0'"
Line 228:"'"
Line 228:"'"
Line 230:"CH"
Line 231:"'0'"
Line 232:"US"
Line 233:"'BatcherUser'"
Line 234:"DT"
Line 235:"to_date('"
Line 235:"','yyyy-MM-dd HH24:mi:ss')"
Line 238:","
Line 239:")"
Line 261:"d"
Line 261:"h"
Line 261:"m"
Line 261:"s"
Line 263:"h"
Line 263:"m"
Line 263:"s"
Line 265:"m"
Line 265:"s"
Line 267:"s"

用作查找目标的Java文件:

package com.hy.insert.multithread;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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;

import com.hy.DBParam;

/**
 * 删单表线程
 * @author 逆火
 *
 * 2019年11月17日 上午9:24:39
 */
public class InsertThread extends Thread{
    private static Logger log = Logger.getLogger(InsertThread.class);

    private final int BatchSize=250;// 一次性插入记录数
    private int tableIndex;// 表序号
    private String tableName;// tablename
    private int count;// record count will be inserted
    private String[] innerArr;// array contains field type and names
    private InsertManager manager;// reference to InsertManager

    /**
     * Constructor
     * @param tableIndex
     * @param tableName
     * @param count
     * @param innerArr
     * @param mng
     */
    public InsertThread(int tableIndex,String tableName,int count,String[] innerArr,InsertManager mng) {
        this.tableIndex=tableIndex;
        this.tableName=tableName;
        this.count=count;
        this.innerArr=innerArr;
        this.manager=mng;
    }

    /**
     * Run body here
     */
    public void run() {
        Connection conn = null;
        Statement stmt = null;

        try{
            long startTime = System.currentTimeMillis();

            Class.forName(DBParam.Driver).newInstance();
            conn = DriverManager.getConnection(DBParam.DbUrl, DBParam.User, DBParam.Pswd);
            stmt = conn.createStatement();
            log.info("Begin to access "+DBParam.DbUrl+" as "+DBParam.User+"...");

            truncateTable(tableName,conn,stmt);
            insertDataToTable(tableIndex,tableName,count,innerArr,conn,stmt);

            if(isAllInserted(count,tableName,stmt)) {
                long endTime = System.currentTimeMillis();
                String timeElasped=sec2DHMS(startTime,endTime);
                log.info("#"+tableIndex+" "+count+" records were inserted to table:'" + tableName + "' used " + timeElasped );

                manager.reportFinished(String.valueOf(tableIndex), tableName, timeElasped);
            }

        } catch (Exception e) {
            System.out.print(e.getMessage());
        } finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                log.error("Can't close stmt/conn because of " + e.getMessage());
            }
        }
    }

    /**
     * judge if all records are inserted
     * @param count
     * @param table
     * @param stmt
     * @return
     * @throws SQLException
     */
    private boolean isAllInserted(int count,String table,Statement stmt) throws SQLException {
        String sql="SELECT COUNT (*) as cnt FROM "+table;

        ResultSet rs = stmt.executeQuery(sql);

        while (rs.next()) {
            int cnt = rs.getInt("cnt");
            return cnt==count;
        }

        return false;
    }

    /**
     * get datetime n seconds before
     * @param n
     * @param interval
     * @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;
        }
    }

    /**
     * delete all data in a table quickly
     * @param tableName
     * @param conn
     * @param stmt
     * @throws SQLException
     */
    private void truncateTable(String tableName,Connection conn,Statement stmt) throws SQLException{
        String sql="truncate table "+tableName;
        stmt.execute(sql);
        log.info("truncated table:"+tableName);
    }

    /**
     * Insert date to a table
     * @param tbSN
     * @param tableName
     * @param count
     * @param innerArr
     * @param conn
     * @param stmt
     * @throws SQLException
     */
    private void insertDataToTable(int tbSN,String tableName,int count,String[] innerArr,Connection conn,Statement stmt) 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<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+" "+BatchSize+" records inserted to '"+tableName+"' used " + sec2DHMS(startTime,endTime));
        }
    }

    /**
     * get insert sql
     * @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("'BatcherUser'");
            }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;
    }

    /**
     * change seconds to DayHourMinuteSecond format
     * @param stratMs
     * @param endMs
     * @return
     */
    private static String sec2DHMS(long stratMs,long endMs) {
        String retval = null;
        long secondCount=(endMs-stratMs)/1000;

        long days = secondCount / (60 * 60 * 24);
        long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
        long minutes = (secondCount % (60 * 60)) / 60;
        long seconds = secondCount % 60;

        if (days > 0) {
            retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
        } else if (hours > 0) {
            retval = hours + "h" + minutes + "m" + seconds + "s";
        } else if (minutes > 0) {
            retval = minutes + "m" + seconds + "s";
        } else {
            retval = seconds + "s"";
        }

        return retval;
    }

    /**
     * Inner class,used for inner data structure
     * @author 逆火
     *
     * 2019年11月17日 上午9:27:47
     */
    protected static final class TypeField{
        String type;
        String field;
    }
}

参考资料:https://www.zhihu.com/question/47381844

--END-- 2019年11月19日21:15:17

【Java.Regex】用正则表达式查找Java文件里的字符串的更多相关文章

  1. linux查找所有文件中某个字符串

    查找目录下的所有文件中是否含有某个字符串 find .|xargs grep -ri "IBM" 查找目录下的所有文件中是否含有某个字符串,并且只打印出文件名 find .|xar ...

  2. 【Java.Regex】用正则表达式查找Java源文件中的注释

    代码: package regex; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.I ...

  3. 正则表达式总结 java 等

    这个经常用的到,就来总结一下 #一下是JAVA中的正则表达式 在 JDK1.4 里有了自己的正则表达式 API 包,JAVA 程序员可以免去找第三方提供的正则表达式库的周折了,我们现在就马上来了解一下 ...

  4. 菜鸡的Java笔记 第二十八 - java 包的定义

    包的主要作用以及定义    包的导入操作    系统常见的开发包    jar 程序命令        包的定义        在任何的操作系统之中都有一个统一的共识:同一个目录下不能够存在有相同的文 ...

  5. Objective-C 【从文件中读写字符串(直接读写/通过NSURL读写)】

    ———————————————————————————————————————————从文件中读写字符串(直接读写/通过NSURL读写) #import <Foundation/Foundati ...

  6. 利用Python从文件中读取字符串(解决乱码问题)

    首先声明这篇学习记录是基于python3的. python3中,py文件中默认的文件编码就是unicode,不用像python2中那样加u,比如u'中文'. 不过在涉及路径时,比如C:\Users\A ...

  7. 从java文件和CS文件里查询方法使用次数工具

    前几天,领导让我找一下老系统(Java)里getRemoteUser方法都哪个文件用了,package是什么,方法被调用了多少次,当时因为着急,所以,直接人工找的,但是以后要是再出现,人工找就太讨厌了 ...

  8. Java查找指定文件中指定字符的个数

    package lwl.youweb2.test; import java.io.BufferedReader; import java.io.FileReader; import java.io.I ...

  9. 《Java虚拟机原理图解》 1.2、class文件里的常量池

    [最新更新:2014/11/11]  了解JVM虚拟机原理 是每个Java程序猿修炼的必经之路. 可是因为JVM虚拟机中有非常多的东西讲述的比較宽泛.在当前接触到的关于JVM虚拟机原理的教程或者博客中 ...

随机推荐

  1. Android笔记(六十八) Fragment总结

    Fragment的产生: 为了适应各种尺寸的屏幕,谷歌推出Fragment,可以把Fragment成Activity的一个组成部分,它拥有自己的生命周期.可以接收并处理用户的各种事件,还可以动态的增删 ...

  2. python之while循环用法举例,break与continue的区别,格式化输出及运算符

    一.while循环的基本结构 while 条件: 代码块(循环体) else: 当上面的条件为假. 才会执行 执行顺序:判断条件是否为真. 如果真. 执行循环体. 然后再次判断条件....直到循环条件 ...

  3. 使用Cloudera Manager部署Spark服务

    使用Cloudera Manager部署Spark服务 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 1>.点击添加服务进入CM服务安装向导 2>.选择需要安装的spa ...

  4. 批处理引擎MapReduce编程模型

    批处理引擎MapReduce编程模型 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. MapReduce是一个经典的分布式批处理计算引擎,被广泛应用于搜索引擎索引构建,大规模数据处理 ...

  5. qingqing的项目

    1 https://www.cnblogs.com/zhangqing979797/p/10147679.html 2 https://www.cnblogs.com/zhangqing979797/ ...

  6. Spring -09 -在Spring工程 中加载 properties 文件 -为某个属性添加注解赋初值

    1.在src 下新建 xxx.properties 文件,不要任意加空格,注明jdbc等标识名!2.在spring 配置文件中先引入xmlns:context,在下面添加2.1如果需要记载多个配置文件 ...

  7. 为什么要使用ConcurrentHashMap

    好久没写过技术性文章了,还是要坚持下去.掌握的知识,能写出来或者是讲给别人听才是真正的掌握了知识,如果不善于给别人讲,实际上还是没有真正掌握相关的知识,挑个简单的写吧. 面试的时候经常会被问到hash ...

  8. Dubbo源码分析(6):Code2

    背景 定义解码和编码方法. Code2是Code的升级版本. 类图 问题 DubboCodec的父类已经实现了Code2接口并且DubboCodec没有实现Code2接口,为什么要implement ...

  9. Spring Boot 2.x实战之定时任务调度

    在后端开发中,有些场景是需要使用定时任务的,例如:定时同步一批数据.定时清理一些数据,在Spring Boot中提供了@Scheduled注解就提供了定时调度的功能,对于简单的.单机的调度方案是足够了 ...

  10. C int类型的数组在内存中的地址示例

    #include <stdio.h> int main(void){ int age[5] = {5,6,7,20,99}; return 0; } //转换后 /*(gdb) p &am ...