标签:
最近要改一个产品到MYSQL数据库,源代码是遗留下来的,里面有很多反编译的文件,并且带有错误。因此想要删掉这些反编译文件,避免干扰。好在这些文件内容里都带有反编译器的信息。通过关键字在ECLIPSE下搜索发现了500+个文件,无奈只好想办法批量删除。首先想到用脚本语言(bat),网上找了一遍,没有合适的,最后决定用JAVA实现。
1 public static String[] findFiles(String baseURL,String... contains){ 2 File baseDIR = new File(baseURL); 3 if(!baseDIR.isDirectory()){ 4 throw new RuntimeException(baseURL +" is nor a dir!"); 5 } 6 ab(baseDIR); 7 return null; 8 } 9 10 private static void ab(File baseDIR) { 11 File[] farr = baseDIR.listFiles(); 12 13 List<File> flist = new ArrayList<File>(); 14 try { 15 flist = Arrays.asList(farr); 16 } catch (Exception e) { 17 e.printStackTrace(); 18 } 19 flist = flist.stream().filter(f->new MyPredicate().test(f)).collect(Collectors.toList());//dir 留下 20 if(flist.size()>0){ 21 for(File f : flist){ 22 ab(f); 23 } 24 } 25 } 26 27 public static void main(String args[]){ 28 Finder.findFiles("D:/work/workspace2/bsp2/src", ""); 29 }
使用了JAVA8 Stream 并发的特性过滤文件列表,现学现卖....
1 package me.ks.main; 2 3 import java.io.File; 4 import java.util.function.Predicate; 5 6 public class MyPredicate implements Predicate<File> { 7 8 @Override 9 public boolean test(File t) { 10 if (t.isDirectory()) { 11 return true; 12 } 13 if (t.getName().endsWith(".java")) { 14 try { 15 StringBuilder sb = RandomAccessFileTest.readLastOfFile(t, 4); 16 if (sb.toString().contains("JD-Core")) { 17 System.out.print(t.getAbsolutePath() + ";"); 18 } 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 } 23 return false; 24 } 25 26 }
反编译工具是JD-GUI ,编译后的文件最后面都 JD-Core 字样,因此要查找文件末尾是否包含JD-Core 字样,代码从网上找的,略作修改:
1 public static StringBuilder readLastOfFile(File f,int lastLineCount) { 2 3 RandomAccessFile randomAccess = null; 4 StringBuilder sb = null; 5 try { 6 randomAccess = new RandomAccessFile( f, "r"); 7 boolean eol = false; 8 int c = -1; 9 long fileLength = randomAccess.length(); 10 long size = 1; 11 int lineCount = 0; 12 ww: while (!eol) { 13 long offset = fileLength - (size++); 14 randomAccess.seek(offset); 15 switch (c = randomAccess.read()) { 16 case -1: 17 case ‘\n‘: 18 case ‘\r‘: 19 randomAccess.seek(offset + 1); 20 if(++lineCount==lastLineCount){ 21 break ww; 22 } 23 } 24 } 25 26 sb = new StringBuilder(); 27 String line; 28 while ((line = randomAccess.readLine()) != null) { 29 sb.append(line); 30 } 31 } catch (FileNotFoundException e) { 32 e.printStackTrace(); 33 } catch (IOException e) { 34 System.err.println(f.getAbsolutePath()); 35 e.printStackTrace(); 36 }finally{ 37 try{ 38 if(randomAccess!=null){ 39 randomAccess.close(); 40 } 41 }catch(Exception e){} 42 } 43 return sb; 44 }
文件列表打到了控制台上,比较懒,拷贝出来再做比批量删除ing....
标签:
原文地址:http://www.cnblogs.com/kevin-talk/p/4503756.html