Java - regex for separating directory paths

I am trying to do the following in Java,
specify the directory path, for example "/a/b/c"I want to get an array of strings 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 an array is also space. I want to get all these lines using length>0.
How should I do it??

+5
source share
4 answers

The only place you get an empty string (in a valid path) will be the first element if the path starts with a delimiter. If he had a leading delimiter, split his path without him.

String path = "/a/b/c";
String[] directories = path.substring(1).split(DIRECTORY_PATH_SEPARATOR);
// { "a", "b", "c" }

OmnipotentEntity, . 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);

:

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());
+4

File, .

+2

String.split(String) , (, ). Guava (Google Core Libraries Java) Splitter, , , :

String path = "/a/b///c///";
Iterable<String> directories = Splitter
    .on(DIRECTORY_PATH_SEPARATOR)
    .omitEmptyStrings()
    .split(path);

, for :

for(String directory : directories) {
  System.out.println(directory);
}

, .

, iterable ArrayList :

List<String> dirList = Lists.newArrayList(directories);
String[] dirArray = Iterables.toArray(directories, String.class);

: File.separator DIRECTORY_PATH_SEPARATOR.

+1

, :

public static List<String> splitFilePath(final File f){
    if(f == null){
        throw new NullPointerException();
    }
    final List<String> result = new ArrayList<String>();
    File temp = f.getAbsoluteFile();
    while(temp != null){
        result.add(0, temp.getName());
        temp = temp.getParentFile();
    }
    return result;
}

:

public static void main(final String[] args){
    final File f = new File("foo/bar/phleem.txt");
    final List<String> parts = splitFilePath(f);
    System.out.println(parts);
}

:

[, home, seanizer, projects, eclipse, helios2, stackfiddler, foo, bar, phleem.txt]

, , , , , :

List<String> parts = splitFilePath(f);
String[] partsAsArray = parts.toArray(new String[parts.size()]);
0

All Articles