Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 247
Nicks Avatar asked May 10 '15 21:05

Nicks


People also ask

What is startsWith method?

The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).

What type of value is return by startsWith () method?

startswith() method returns a boolean. It returns True if the string starts with the specified prefix.

How do you use string Startwith?

JavaScript String startsWith() The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.

Is startsWith case sensitive Java?

startsWith method is case sensitive.


1 Answers

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

like image 191
Jeffrey Bosboom Avatar answered Oct 02 '22 19:10

Jeffrey Bosboom