How do you get the length of a Path? Am I missing something here? Strangely enough, int length() nor any similar method is implemented in the Path class. Example: for the path
C:\foo\bar\anotherfolder\subfolder
the method would return 4.
Path length is simply the distance between two nodes, measured as the number of edges between them. If Amy is Brad's friend, and Brad is Calvin's friend, then the path length between Amy and Calvin is 2.
To calculate the length of a string in Java, you can use an inbuilt length() method of the Java string class. In Java, strings are objects created using the string class and the length() method is a public member method of this class. So, any variable of type string can access this method using the . (dot) operator.
In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.
Path.getNameCount():
Returns the number of name elements in the path.
you can use count total number of backslash in the string which will give you same answer Like this
StringTokenizer stOR = new StringTokenizer("C:\foo\bar\anotherfolder\subfolder", "\");
If you are using windows system then you need to append extra backslash for each. Otherwise your string will give compile time error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
int orCount = stOR.countTokens()-1;
System.out.println(orCount);
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