判断.java文件中getConnection与cleanUp数量是否匹配

需求:查找未关闭的数据库连接。

两步走:

1.将给定目录下的及子目录下的 所有的给定后缀名的文件路径存到集合中。

2.使用正则表达式对每个文件进行匹配。

package com.fanc.main;



import java.io.File;

import java.io.FileInputStream;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.regex.Matcher;

import java.util.regex.Pattern;



public class Search4NotMatch {



	/**

	 * 

	 * 深度遍历该父目录,将给定目录下的及子目录下的 所有的给定后缀名的文件路径存到集合中。(进行过滤)。

	 *

	 * 遍历集合对每个文件进行匹配,需求是判断每个文件中的getConnection和cleanUp数目是否相等

	 *

	 */

	public static void main(String[] args) {

		//指定目录

		String filePath = "你需要指定的目录";

		File dir = new File(filePath);

	

		ArrayList<File> path = new ArrayList<File>();



		writeToArr(dir,  path);



		Iterator<File> it = path.iterator();



		while (it.hasNext()) {



			File file = (File) it.next();

			if (!deal(file)) {



				System.out.println(file);

			}



		}



	}



	public static void writeToArr(File dir,

			ArrayList<File> al) {



		File[] files = dir.listFiles();

		for (File f : files) {

			if (f.isDirectory()) {

				// 递归 遍历父目录及其子目录

				writeToArr(f, al);

			} else {

				if (f.getName().endsWith(".java")) {

					al.add(f);

				}

			}

		}

	}



	// 判断.java文件中getConnection与cleanUp数量是否匹配

	public static boolean deal(File file) {



		String str = null;



		try {



			FileInputStream fis = new FileInputStream(file);



			byte[] content = new byte[fis.available()];



			fis.read(content);



			str = new String(content);



		} catch (Exception e) {

			// TODO: handle exception

			e.printStackTrace();

		}



		int getConnectionNumber = 0;

		int cleanUpNumber = 0;



		Pattern p1 = Pattern.compile("getConnection");

		Pattern p2 = Pattern.compile("cleanUp");



		Matcher m1 = p1.matcher(str);

		Matcher m2 = p2.matcher(str);



		while (m1.find()) {

			getConnectionNumber++;

		}



		while (m2.find()) {

			cleanUpNumber++;

		}



		if (getConnectionNumber != cleanUpNumber) {

			return false;

		} else {

			return true;

		}

	}

}

  

你可能感兴趣的:(Connection)