简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM