Reputation: 2938
I have to be misunderstanding this. Given the following code, I expect a "they match" printout. I get "oops. no match."
Path p = Paths.get("C:\\fakename");
Path q = Paths.get("C:\\fake");
if(p.startsWith(q))
{
System.out.println("they match");
}
else
{
System.out.println("oops. no match.");
}
What am I misunderstanding? The documentation seems pretty clear.
Upvotes: 3
Views: 2297
Reputation: 21
p and q are from Type "Path". If you want to use startsWith() you need the type "String".
so try this:
package newTestPackage.Contains;
import java.nio.file.Path; import java.nio.file.Paths;
public class testwise {
public static void main(String[] args) {
Path p = Paths.get("C:\\fakename");
Path q = Paths.get("C:\\fake");
if(p.toString().startsWith(q.toString()))
{
System.out.println("they match");
}
else
{
System.out.println("oops. no match.");
}
}
}
It`s my first answer here. I hope I was able to help you. :-)
Upvotes: 2
Reputation: 48404
Path
comparison is not String
comparison.
String.startsWith
take a single String
argument representing any String
contained within your target at its beginning.
Path.startsWith(String other)
...
Tests if this path starts with a Path, constructed by converting the given path string, in exactly the manner specified by the startsWith(Path) method. On UNIX for example, the path "foo/bar" starts with "foo" and "foo/bar". It does not start with "f" or "fo".
(quoted from API).
Upvotes: 5
Reputation: 27356
It won't perform a startsWith
on the folder name too. They don't start with the same path, hence the false
.
Upvotes: 1
Reputation: 160211
But not clear enough, apparently.
Path comparisons check at the path element level, not the string level.
Upvotes: 1
Reputation: 4086
According to the documentation you linked :
the path "foo/bar" starts with "foo" and "foo/bar". It does not start with "f" or "fo".
Upvotes: 1
Reputation: 121750
What am I misunderstanding?
Well, the documentation states this:
This path starts with the given path if this path's root component starts with the root component of the given path, and this path starts with the same name elements as the given path
And fake
isn't the same name element as fakename
!
Upvotes: 10