Close

Java - How to split file path by file separator character?

[Last Updated: May 31, 2018]

Java IO & NIO Java 

Following example shows how to split a file path string by system path separator. The example uses java.nio.file.Path.
Path implements Iterable, so we can convert it to a stream and then convert to a String array.

package com.logicbig.example;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.StreamSupport;

public class SplitPathUtil {
  public static String[] splitPath(String pathString) {
      Path path = Paths.get(pathString);
      return StreamSupport.stream(path.spliterator(), false).map(Path::toString)
                          .toArray(String[]::new);
  }

  public static void main(String[] args) throws IOException {
      String pathString = System.getProperty("java.io.tmpdir");
      System.out.println(pathString);
      String[] paths = splitPath(pathString);
      System.out.println(Arrays.toString(paths));
  }
}
C:\Users\Joe\AppData\Local\Temp\
[Users, Joe, AppData, Local, Temp]

See Also