Malcolm Wright
Malcolm Wright

Reputation: 27

JAVA path.getName(0) returning the entire path instead of first element on a Mac, with windows path

I suspect this is a noob mistake on my behalf. With Java 13 and the following method:

    public static void winPath (){
        Path winPath = Paths.get("C:\\the\\wizards\\despicable\\cat");
        System.out.println(String.format("First element of %s is: %s", winPath.toString(), winPath.getName(0)));
    }

Calling this method, I would expect to get:

First element of C:\the\wizards\despicable\cat is: the

Instead I get the entire path:

First element of C:\the\wizards\despicable\cat is: C:\the\wizards\despicable\cat

This is unexpected behaviour to me, because if I try the same with a macos path:

 public static void macPath (){
        Path macpath = Paths.get("/Volumes/Multimedia/the/wizards/despicable/cat");
        System.out.println(String.format("First element of %s is: %s", macpath.toString(), macpath.getName(0)));
    }

... the output is as I hoped for:

First element of /Volumes/Multimedia/the/wizards/despicable/cat is: Volumes

Any help would be appreciated!

Upvotes: 0

Views: 270

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51972

Path will not divide your string into different elements when you execute this on a non Windows system because it doesn't recognise the file separator, so to create a path where each disk/folder/file is different element you need to create it like this

Path winPath = Paths.get("C:", "\\the", "\\wizards", "\\despicable", "\\cat");

or even better since you don't want the \ included

Path winPath = Paths.get("C:", "the", "wizards", "despicable", "cat");

Then you can iterate over your elements

winPath.forEach( p ->
    System.out.println(p)
);

This is why your second example works as expected when run on a Mac (or a Linux/Unix) machine

Paths.get("/Volumes/Multimedia/the/wizards/despicable/cat");

will split the given path into different elements, "Volume", "Multimedia" and so on

Upvotes: 1

Related Questions