Java I/O How to - Get the folder/directory for each part of a full path








Question

We would like to know how to get the folder/directory for each part of a full path.

Answer

import java.nio.file.FileSystems;
import java.nio.file.Path;
//w  w  w.  j  av a 2s . c  o  m
public class Main {

  public static void main(String[] args) {
    Path path = FileSystems.getDefault().getPath("/home/docs/status.txt");
    System.out.printf("getNameCount: %d\n", path.getNameCount());
    for (int index = 0; index < path.getNameCount(); index++) {
        System.out.printf("getName(%d): %s\n", index, path.getName(index));
    }
  }
}

The code above generates the following result.