Why is "Path.startsWith" behavior different from "String.startsWith" behavior - 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 filename starts with "Ver". There C:/books
are two files in the directory that start with "Ver", Version.yxy
and Version1.txt
. I tried to use 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;
}
}
Output of the above code:
false Version.txt
false Version1.txt
source to share
Path.getFileName()
returns Path
containing just the filename. Path.startsWith
checks if a path starts with the same sequence of path components - a boolean rather than a text operation. startsWith
Javadoc explicitly:
On UNIX, for example, the path "foo / bar" starts with "foo" and "foo / bar". It doesn't start with "f" or "fo".
If you just want to check the text start-with-ness, are first converted to String, by calling toString()
: Path.getFileName().toString().startsWith("Ver")
.
source to share