javawindowsjsr203

Represent a `Path` starting with a `\` but without a disk drive, under Windows


I do not own a Windows copy, but would like to know the behavior and recommended usage in Java for representing a path such as \autoexec.bat under Windows?

Semantically, such a path would represent the file autoexec.bat on the root of any file system. Thus it would need to be resolved against a path representing a disk drive (such as C:\) before representing a file. In that sense, it is not absolute. However, it also does not have a root component, I suppose.

Can such path be created when running the JVM on Windows? If so, what would getRoot() and isAbsolute() return?

I tried the following code using Memory File System, but this throws InvalidPathException: “path must not start with separator at index 1: \truc”. Does this faithfully reflect the behavior under Windows, or is it a quirk of this specific library?

try (FileSystem fs = MemoryFileSystemBuilder.newWindows().build()) {
    final Path truc = fs.getPath("\\truc");
    LOGGER.info("Root: {}.", truc.getRoot());
    LOGGER.info("Abs: {}.", truc.isAbsolute());
    LOGGER.info("Abs: {}.", truc.toAbsolutePath());
}

Such paths are valid in the Windows terminal, or at least they were last time I used Windows (a long time ago). It would be handy to create such path in order to mark that the path is “absolute” (in the sense of starting with a backslash, thus not relative to a folder), but still leave the path without a driver letter specified. Then such a path can be (later) resolved to C:\autoexec.bat or D:\autoexec.bat or …


Solution

  • In Windows, \\ refers to the current drive which is C:\ in my case.

    Not sure how the MemoryFileSystemBuilder works but the following code

    File file = new File("\\test.txt");
    final Path truc = file.toPath();
    System.out.println("Root: " + truc.getRoot().toString());
    System.out.println("Abs: " + truc.isAbsolute());
    System.out.println("Abs: " + truc.toAbsolutePath().toString());
    

    gives the below output

    Root: \
    Abs: false
    Abs: C:\test.txt