I am trying to do the following in Java
give a directory path like "/a/b/c"
I want to get a array of string as ["a", "b", "c"]
. The code is as follows :
private static final String DIRECTORY_PATH_SEPARATOR = "/";
Iterator iter = testPaths.iterator();
String[] directories;
while( iter.hasNext() ) {
directories = ( ( String ) iter.next() ).split(DIRECTORY_PATH_SEPARATOR);
}
but what i get as array is space as well. I want to get all those strings with length>0
.
how can I do that??
The only place you'd get an empty string (in a valid path) would be the first item if the path started with the separator. If it had the leading separator, split on the path without it.
String path = "/a/b/c";
String[] directories = path.substring(1).split(DIRECTORY_PATH_SEPARATOR);
// { "a", "b", "c" }
As noted by OmnipotentEntity, my assumption was wrong about valid paths. You'd otherwise have to go through the array and keep nonempty strings when using split()
.
String path = "/a/b////c";
String[] split = path.split(DIRECTORY_PATH_SEPARATOR);
ArrayList<String> directories = new ArrayList<String>(split.length);
for (String dir : split)
if (dir.length() > 0)
directories.add(dir);
An alternative is to use actual regular expressions to match non-separator characters:
String path = "/a/b////c";
ArrayList<String> directories = new ArrayList<String>();
Pattern regex = Pattern.compile("[^" + DIRECTORY_PATH_SEPARATOR + "]+");
Matcher matcher = regex.matcher(path);
while (matcher.find())
directories.add(matcher.group());
You should use the File class for this, not a regex.
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