java file模糊匹配某文件夹下的文件并删除

来源:互联网 发布:西南seo大神 编辑:程序博客网 时间:2024/06/05 21:02
package com.wyebd.gis;import java.io.File;/**    * @Title: DelFiles.java * @Package com.wyebd.gis * @Description:  * @author lisr * @date Mar 7, 2012 5:36:03 PM     * @version V1.0    */public class DelFiles { /**  * @Title: main  * @Description:   * @param args  * @return void   * @author lisr  * @date Mar 7, 2012 5:36:04 PM  * @throws  */ //用以模糊删除头部为str的文件 public static boolean delFilesByPath(String path,String str){  //参数说明---------path:要删除的文件的文件夹的路径---------str:要匹配的字符串的头  boolean b=false;  File file = new File(path);   File[] tempFile = file.listFiles();   for(int i = 0; i < tempFile.length; i++){    if(tempFile[i].getName().startsWith(str)||tempFile[i].getName().endsWith(str)){     System.out.println("将被删除的文件名:"+tempFile[i].getName());    boolean del=deleteFile(path+tempFile[i].getName());    if(del){     System.out.println("文件"+tempFile[i].getName()+"删除成功");     b=true;    }else{     System.out.println("文件"+tempFile[i].getName()+"删除失败");    }   }  }  return b; }  private static boolean deleteFile(String path){  System.out.println(path);  boolean del=false;  File file=new File(path);  if(file.isFile()){   file.delete();   del=true;  }  return del; }  public static void main(String[] args) {  // TODO Auto-generated method stub  String path="D:/temp/";  String str="44_";  if(delFilesByPath(path,str)){   System.out.println(path+"中包含"+str+"的文件已经全部删除成功!");  }else{   System.out.println(path+"中包含"+str+"的文件已经删除失败或该文件夹下不存在这类文件!");  } }}  ================================================================================================================================================================package com.wyebd.gis;import java.io.File;/**    * @Title: DelFiles.java * @Package com.wyebd.gis * @Description:  * @author lisr * @date Mar 7, 2012 5:36:03 PM     * @version V1.0    */public class DelFiles { /**  * @Title: main  * @Description:   * @param args  * @return void   * @author lisr  * @date Mar 7, 2012 5:36:04 PM  * @throws  */ //用以模糊删除头部为str的文件 public static boolean delFilesByPath(String path,String str){  //参数说明---------path:要删除的文件的文件夹的路径---------str:要匹配的字符串的头  boolean b=false;  File file = new File(path);   File[] tempFile = file.listFiles();   for(int i = 0; i < tempFile.length; i++){    if(tempFile[i].getName().startsWith(str)||tempFile[i].getName().endsWith(str)){     tempFile[i].delete();    b=true;   }  }  return b; } public static void main(String[] args) {  String path="D:/temp/";  String str="44_";  if(delFilesByPath(path,str)){   System.out.println(path+"中包含"+str+"的文件已经全部删除成功!");  }else{   System.out.println(path+"中包含"+str+"的文件已经删除失败或该文件夹下不存在这类文件!");  } }}个人认为:如果要实现更高级的这种模糊匹配,只需要用String的indexOf()方法,凡是含有这个字符串的文件,都一并删除!


转载:http://blog.csdn.net/lishirong/article/details/41674511

0 0
原创粉丝点击