How to check the extension of a Java 7 Path

前端 未结 4 1179
温柔的废话
温柔的废话 2020-12-08 03:23

I\'d like to check if a Path (introduced in Java 7) ends with a certain extension. I tried the endsWith() method like so:

Path path = Paths.get         


        
4条回答
  •  悲&欢浪女
    2020-12-08 04:05

    Simple solution:

    if( path.toString().endsWith(".java") ) //Do something
    

    You have to be carefull, when using the Path.endsWith method. As you stated, the method will return true only if it matches with a subelement of your Path object. For example:

    Path p = Paths.get("C:/Users/Public/Mycode/HelloWorld.java");
    System.out.println(p.endsWith(".java")); // false
    System.out.println(p.endsWith("HelloWorld.java")); // true
    

提交回复
热议问题