对于一个文件名的使用经常要做一些判断,比如文件名是否是指定的名字,或者文件是否为指定的类型,或者筛选出以指定后缀结尾的文件名,等等
这时就可以提取出文件名的字符串进行比较判断筛选
在java中的String类的一些常用方法中给出了这些工具方法,比如判断两个字符串是否一致,字符串是否以指定的前缀开始,字符串是否以指定的后缀结束等等方法
这里用到的java中的String类的常用方法
boolean equals(Object obj):比较字符串是否相同
boolean endWith(String str):测定字符串是否以指定的后缀结束
通过这两个方法进行筛选
String par1 = “params.txt”;
String par2 = “_depth.dep”;
String par3 = “_GRD.grd”;
String par4 = “_cs.dep”;
String par5 = “_Tide.txt”;
String par6 = “Jonswap.txt”;
判断文件名是否为params.txt,Jonswap.txt,或者以指定的后缀_depth.dep,_GRD.grd,_cs.dep,_Tide.txt结尾的文件

public class FileTest {
    public static void main(String[] args) {
        String par1 = "params.txt";
        String par2 = "_depth.dep";
        String par3 = "_GRD.grd";
        String par4 = "_cs.dep";
        String par5 = "_Tide.txt";
        String par6 = "Jonswap.txt";
        while(true) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("please pressure a filename:");
            String next = scanner.next();
            if ("exit".equals(next)){
                break;
            }else if(par1.equals(next) || par2.endsWith(next) || par3.endsWith(next)
                    || par4.endsWith(next) || par5.endsWith(next) || par6.equals(next))
            {
                System.out.println("找到了你输入的文件:" + next);
            }else{
                System.out.println("没有找到!");
            }
        }
    }
}


以上代码虽然可以正常运行输出,但是它不仅匹配了后缀,只要是最后一个字母一样的它都可以匹配上,所以多多少少有一点bug,这里的解决方法是使用正则表达式的方法,在java中的String类中也提供了使用正则表达式匹配的方法
boolean mathes(String regex):告知此字符串是否匹配给指定的正则表达式
首先了解必须的正则表达式原则
** . :通配所有的字符**
** * :匹配0次或者多次前面出现的正则表达式**
** + :匹配1次或者多次前面出现的正则表达式**
** ?:匹配0次或者1次前面出现的正则表达式**
** re1 | re2 :匹配正则表达式re1或者re2**
所以在制定后缀的正则表达式写法:

.*_cs//.dep

上面代码就是匹配后缀为_cs.dep,前面可以有内容,也可以没有内容的文件名

.*_cs//.dep|.*_GRD.grd

上面代码就是匹配两个正则表达式,或者re1或者re2
了解了这两个写法之后,就可以进行匹配了:

public class RegexTest2 {
    public static void main(String[] args) {
        String regex = ".*_GRD\\.grd|.*_cs\\.dep|.*_depth\\.dep|" +
                ".*_Tide\\.txt|params\\.txt|Jonswap\\.txt";
        while(true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("please preesure a fileName:");
            String next = scanner.next();
            if (next.matches(regex)){
                System.out.println("找到了:" + next);
            }else if("exit".equals(next)){
                System.out.println("byebye...");
                break;
            }else{
                System.out.println("没有找到!");
            }
        }
    }
}


以上就完成了!

更多推荐

使用正则表达式查找指定字符串