Java Programming Tutorials

Java programming tutorials with many code examples!

Java filename from Path

Java filename from Path

In this tutorial we’re going to show how to get filename from Java 7 Path. The new, flexible API offers more choices to that.

Filename from Path using Path.getFileName()

This is the simplest way to obtain filename from Path:

Path path = Paths.get("/proc/version");
System.out.println("path.getFileName(): "
    + path.getFileName().toString());

The above code produces:

path.getFileName(): version

Taking filename using Path.getName()

In this approach we can get any part of path, including filename:

Path path = Paths.get("/proc/version");
System.out.println("number of name parts: " + path.getNameCount());
System.out.println("path.getName(0): " + path.getName(0));
System.out.println("path.getName(1): " + path.getName(1));

It gives the following output:

number of name parts: 2
path.getName(0): proc
path.getName(1): version

Note: remove redundant elements from Path before getting its parts!


Check out Java IO Tutorial to learn more about Java NIO!

Share with the World!