java遍历文件夹找到所有get方法
import java.io.File; import java.io.IOException; import java.util.Scanner; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.FileNotFoundException; public class B { static int m=1; static void search(File a,String x) throws IOException{//在文件a中的每行中查找x Scanner scan = new Scanner(a,"utf-8"); int k = 0; Pattern p = Pattern.compile("\bget[A-Z][A-Z]"); Matcher matcher = null; boolean isValid = false; while(true){ if(scan.hasNext()==false) break; String s = scan.nextLine(); k++; //存在get方法 if(s.contains(x)){ //匹配以get开头,后续是两个大写字母的规则 matcher = p.matcher(s); isValid = matcher.matches(); if(isValid){ String ss =m +".文件:"+ a.getPath() + " 第" + k + "行 \n 内容:" + s; System.out.println(ss); m++; } } } Scanner scan1 = new Scanner(a,"utf-8"); int k1 = 0; while(true){ if(scan1.hasNext()==false) break; String s1 = scan1.nextLine(); k1++; if(s1.contains(x)){ String ss1 =m +".文件:"+ a.getPath() + " 第" + k1 + "行 \n 内容:" + s1; System.out.println(ss1); m++; } } } static void f(File a,String s)throws IOException{//在a下所有文件中查找含有s的行 File[] ff = a.listFiles(); if(ff==null) return; for(File it : ff){ if(it.isFile()){//若a是文件,直接查找 search(it,s); } if(it.isDirectory()){//若a是目录,则对其目录下的目录或文件继续查找 f(it,s); } } } public static void main(String[] args)throws IOException { File f=new File("e://out.txt"); FileOutputStream fileOutputStream = new FileOutputStream(f); PrintStream printStream = new PrintStream(fileOutputStream); System.setOut(printStream); System.out.println("默认输出到控制台的这一句,输出到了文件 out.txt"); f(new File("e:\\myeclipse\\workspace\\sms\\src\\com")," get"); } }
学如逆水行舟,不进则退