Why is 'Path.startsWith' behaviour different from a 'String.startsWith' operation - even for 'Path.getFilename'
Asked Answered
S

1

5

I am using Java version 1.8.0_31.

I am trying to recursively access a directory tree using the FileVisitor interface. The program should print the name of all files in C:/books whose file name starts with "Ver". The directory C:/books has two files that starts with "Ver", Version.yxy and Version1.txt. I tried using file.getFileName().startsWith("Ver") but this returns false.

Am I missing something? Here's my code:

public class FileVisitorTest {

    public static void main(String[] args) {

        RetriveVersionFiles vFiles = new RetriveVersionFiles();
        try {
            Files.walkFileTree(Paths.get("c:", "books"), vFiles);
        } catch (IOException e) {
            // TODO Auto-generated catch block
         e.printStackTrace();
        }
    }
}

class RetriveVersionFiles extends SimpleFileVisitor<Path> {

    public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
        System.out.println(file.getFileName().startsWith("Ver") + " "
              + file.getFileName());
        if (file.getFileName().startsWith("Ver")) {
            //not entering this if block
            System.out.println(file);
        }
        return FileVisitResult.CONTINUE;
   }
}

The output of the above code is:

false Version.txt
false Version1.txt
Samovar answered 10/5, 2015 at 21:57 Comment(0)
P
11

Path.getFileName() returns a Path containing just the file name. Path.startsWith checks if the path starts with the same sequence of path components -- a logical, not textual, operation. The startsWith Javadoc is explicit:

On UNIX for example, the path "foo/bar" starts with "foo" and "foo/bar". It does not start with "f" or "fo".

If you just want to check for textual starts-with-ness, first convert to a String by calling toString(): Path.getFileName().toString().startsWith("Ver").

Portland answered 10/5, 2015 at 22:7 Comment(2)
Thank You, sounds logical and worked too. I actually was referring KathySierra book for java certification, page 515, they gave example as, if ( file.getFileName().endsWith(".class")) Files.delete(file);...and seems its an issue.Samovar
If I designed the API, I wouldn't've added the overload taking a String. It's too easy to make this mistake.Portland

© 2022 - 2024 — McMap. All rights reserved.