Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of a Path in java?

Tags:

java

path

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.

like image 543
Sargon1 Avatar asked Dec 11 '15 16:12

Sargon1


People also ask

How do you find the length of a path?

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.

How do you find the length of a line in Java?

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.

How do I find the path in Java?

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.


2 Answers

Path.getNameCount():

Returns the number of name elements in the path.

like image 76
Andy Turner Avatar answered Oct 11 '22 03:10

Andy Turner


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);

like image 41
Devender Kumar Avatar answered Oct 11 '22 04:10

Devender Kumar