Java getName(0)使用windows路径返回整个路径,而不是Mac上的第一个元素

Java getName(0)使用windows路径返回整个路径,而不是Mac上的第一个元素,java,windows,path,Java,Windows,Path,我怀疑这是我的错。使用Java 13和以下方法: 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.

我怀疑这是我的错。使用Java 13和以下方法:

    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)));
    }
调用此方法,我希望得到:

First element of C:\the\wizards\despicable\cat is: the
相反,我得到了整个路径:

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

这对我来说是意外的行为,因为如果我在macos路径上尝试同样的行为:

 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)));
    }

。。。结果正如我所希望的:

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


任何帮助都将不胜感激

Path
在非Windows系统上执行此操作时,不会将字符串划分为不同的元素,因为它无法识别文件分隔符,因此要创建一个每个磁盘/文件夹/文件都是不同元素的路径,您需要像这样创建它

Path winPath = Paths.get("C:", "\\the", "\\wizards", "\\despicable", "\\cat");
或者更好,因为您不希望包含\项

Path winPath = Paths.get("C:", "the", "wizards", "despicable", "cat");
然后可以迭代元素

winPath.forEach( p ->
    System.out.println(p)
);
这就是为什么您的第二个示例在Mac(或Linux/Unix)机器上运行时能够正常工作的原因


将给定的路径拆分为不同的元素,“音量”、“多媒体”等等

您现在使用的是哪个版本的jdk?我无法在Java 11中复制,谢谢-我将把这些信息添加到问题中。它是Java 13,也不能在Java 14上复制。这将是非常有意义的,除非我使用macos unix风格的路径,如:/Volumes/Multimedia/the/wizards/skistable/cat,相同的方法返回:Volumes我将更新我的问题以包括这一点……我已经解释了问题所在(第一个版本)我只是不明白为什么当输入一个描述整个Macos路径的字符串时,Path类会标记路径,但是当输入一个描述windows路径的字符串时,它不会标记路径。行为不一致?对不起,我刚意识到这是问题所在。问题是本地人是什么。在Mac上,java将“/”识别为分隔符,因此它可以正确分割路径,但不识别“\”,因此它将整个字符串视为一个路径项。但Mac上的路径永远不会是C:\\the\…,path类用于在其执行的OS(文件系统)上正确处理路径。所以它并不真正了解Windows、MacOS或Linux。
Paths.get("/Volumes/Multimedia/the/wizards/despicable/cat");