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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.
If I designed the API, I wouldn't've added the overload taking a String. It's too easy to make this mistake.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.