Sargon1
Sargon1

Reputation: 874

How to get the length of a Path in java?

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.

Upvotes: 8

Views: 3986

Answers (2)

Devender Kumar
Devender Kumar

Reputation: 545

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

Upvotes: 2

Andy Turner
Andy Turner

Reputation: 140299

Path.getNameCount():

Returns the number of name elements in the path.

Upvotes: 22

Related Questions