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 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).
startswith() method returns a boolean. It returns True if the string starts with the specified prefix.
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.
startsWith method is case sensitive.
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")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With