Search code examples
javanio

java nio path can't handle windows network path


Why does this happen?

def path=java.nio.file.Paths.get("c:/kittuhomestore/Csmart/files/companies");
path.getNameCount();
4

def path=java.nio.file.Paths.get("//kittuhomestore/Csmart/files/companies");
path.getNameCount();
2

The latter is a windows shared network drive.


Solution

  • Path path = java.nio.file.Paths.get("c:/kittuhomestore/Csmart/files/companies");
    System.err.println(path.getRoot());
    

    Output:

    c:\
    

    In the first case, the Root of the path is C:\, so the remaining parts are kittuhomestore, Csmart, files and companies, hence 4 components.


    Path path = java.nio.file.Paths.get("//kittuhomestore/Csmart/files/companies");
    System.err.println(path.getRoot());
    

    Output:

    \\kittuhomestore\Csmart\
    

    In the second case, the Root of the path is \\kittuhomestore\Csmart\, so the remaining parts are files and companies, hence 2 components.

    This is because an UNC path has the format

    \\server\share\file_path
    

    where \\server\share is the root of the path.