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
The Coordinator
  • 13,007
  • 11
  • 44
  • 73
Nicks
  • 16,030
  • 8
  • 58
  • 65

1 Answers1

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").

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
  • 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. – Nicks May 10 '15 at 23:36
  • 3
    If I designed the API, I wouldn't've added the overload taking a String. It's too easy to make this mistake. – Jeffrey Bosboom May 10 '15 at 23:51