代码:

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秒

斜杠星注释::*/

斜杠星注释::/**
     * 将秒转化为日时分秒
     * @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();*/

            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

【Java.Regex】用正则表达式查找Java源文件中的注释的更多相关文章

  1. 【Java.Regex】用正则表达式查找Java文件里的字符串

    代码: import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; imp ...

  2. grep 查找bash脚本中的注释代码

    出于安全性的考虑,不建议在bash脚本中注释掉不使用的代码.也就是说如果某段代码不使用了,那么应该删除掉,而不是简单地注释掉.假如你突然意识到这一点,而以前并没有遵从这个原则,现在需要找出脚本中的注释 ...

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

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

  4. 【Java.Regex】使用正则表达式查找一个Java类中的成员函数

    代码: import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; imp ...

  5. 正则表达式在Java中的使用

    目录 介绍 从简单例子认识正则表达式匹配 Java中对正则表达式的支持(各种语言有相应的实现) 初步认识 . + * ? 范围 认识\s \w \d - 下面介绍数字和字母的正则表达, 这是编程中使用 ...

  6. 浅谈为什么一个java源文件中只能有一个public类?

    声明,本篇文章为转载 转载 http://blog.csdn.net/bareheadzzq/article/details/6562211 最近在一个java文件中实现了几个类,其中一个声明为pub ...

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

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

  8. 一个java源文件中为什么只能有一个public类。

    我们都遇到过一个源文件中有多个java类,但当第一个类使用public修饰时,如果下面还有类使用public修饰,会报错.也就是是说一个java源文件最多只能有一个public类. 当有一个publi ...

  9. java---面试题---.java"源文件中可以包括多个类(不是内部类)

    答题时,先答是什么,再答有什么作用和要注意什么 一个".java"源文件中可以有多个类,但只能有一个public的类,并且public的类名必须与文件名相一致,main方法只能写在 ...

随机推荐

  1. cmd xcopy进行远程复制

    首先  win+R 打开cmd 1  目标远程服务器 查看共享的文件夹 net share 2 与远程建立连接 net use \\192.168.3.200\ipc$ Yhxwl123456 /us ...

  2. linux系统编程之信号(三)

    今天继续对信号进行研究,话不多说,言归正传: 更多信号发送函数: 上节中我们已经接触到了一些信号的发送函数,这里更进一步学习一下其它的发送函数: alarm:只能发送SIGALRM信号 下面通过一个例 ...

  3. 配置logback日志管理的时候

    在使用logback时候,需要引入 thymeleaf的配置 thymeleaf: suffix: .html check-template-location: true encoding: UTF- ...

  4. 图解TCP/IP笔记

  5. oracle lock

    数据库锁介绍:  https://www.cnblogs.com/springsnow/p/9990295.html#_label2_0 总结1:查询oracle锁定的表: 1.锁相关表 SELECT ...

  6. 分段三次Hermite插值及其与三次样条的比较

    分段三次 Hermite 插值多项式 (PCHIP) 语法 p = pchip(x,y,xq) pp = pchip(x,y)   说明 p = pchip(x,y,xq) 返回与 xq 中的查询点对 ...

  7. HttpMessageConverter(消息转换器 )和@responsebody使用(转)

    @responsebody表示该方法的返回结果直接写入HTTP response body中 一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@resp ...

  8. [Svelte 3] Use await block to wait for a promise and handle loading state in Svelte 3

    Most web applications have to deal with asynchronous data at some point. Svelte 3 apps are no differ ...

  9. 洛谷 P2827 蚯蚓 题解

    每日一题 day32 打卡 Analysis 我们可以想一下,对于每一秒除了被切的哪一个所有的蚯蚓都增长Q米,我们来维护3个队列,队列1表示最开始的蚯蚓,队列2表示每一次被切的蚯蚓被分开的较长的那一部 ...

  10. Deepgreen/Greenplum 删除节点步骤

    Deepgreen/Greenplum删除节点步骤 Greenplum和Deepgreen官方都没有给出删除节点的方法和建议,但实际上,我们可以对节点进行删除.由于不确定性,删除节点极有可能导致其他的 ...