My name is Zemian Deng, and I am a Senior Application Engineer working at Oracle for the Enterprise Knowledge Management product. NOTE: The views expressed on my blog and social network are my own and do not necessarily reflect the views of my employer. Zemian is a DZone MVB and is not an employee of DZone and has posted 84 posts at DZone. You can read more from them at their website. View Full User Profile

Be Careful with Java Path.endsWith(String) Usage

04.19.2014
| 4323 views |
  • submit to reddit

If you need to compare the java.io.file.Path object, be aware that Path.endsWith(String) will ONLY match another sub-element of Path object in your original path, not the path name string portion! If you want to match the string name portion, you would need to call the Path.toString() first. For example

// Match all jar files.
Files.walk(dir).forEach(path -> {
if (path.toString().endsWith(".jar"))
System.out.println(path);
});


With out the "toString()" you will spend many fruitless hours wonder why your program didn't work.

Published at DZone with permission of Zemian Deng, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Oleksandr Alesinskyy replied on Wed, 2014/04/23 - 9:09am

 While it's true that

path.toString().endsWith(".jar") 

will return false the reasons are very different from explained by author - it is not because the path name string portion is ignored, but because only whole elements are matched as may be seen from this code 

import java.io.File;

public class TP {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(new File("c:/t/x.jar").toPath().endsWith("x.jar"));
        System.out.println(new File("c:/t/x.jar").toPath().endsWith(".jar"));
    }
}

The output is
true
false

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.