Home > OS >  On Windows, file starting with / is not considered absolute
On Windows, file starting with / is not considered absolute

Time:04-21

This surprised me, but apparently, a path on Windows that starts with a slash is not considered absolute. You need to specify c:. But surely, there is a difference between /foo and foo

System.out.println(new File(new File("/folder"), "abc"));
System.out.println(new File(new File("/folder"), "abc").isAbsolute());

\folder\abc
false

Is this correct behavior?

I want to be able to identify a relative path, such as foo, so I can prepend a default directory. But I would consider /foo to be an absolute path and would not prepend the default

CodePudding user response:

You don't need to check for "isAbsolute" by string comparisons, just use Path and resolve using defaultDir.resolve(path)

Consider:

var rel = Path.of("relative");
var abs = Path.of("/absolute");

for (Path dir : List.of(Path.of("."), Path.of("abc"),Path.of("/abc"))) {
    System.out.println("dir=" dir);
    System.out.println("dir.resolve(" abs ")=" dir.resolve(abs));
    System.out.println("dir.resolve(" rel ")=" dir.resolve(rel));
}

This handles resolving from the default directory path using another path which may be relative or absolute (in sense that it starts with path separator) on Windows or Linux.

Example run from Linux (Windows is same answer but with Windows path separator character).

dir=.
dir.resolve(/absolute)=/absolute
dir.resolve(relative)=./relative
dir=abc
dir.resolve(/absolute)=/absolute
dir.resolve(relative)=abc/relative
dir=/abc
dir.resolve(/absolute)=/absolute
dir.resolve(relative)=/abc/relative

CodePudding user response:

You can check if the start of your file path begins with a "/" using Boolean isPathAbsolute = "/foo".startsWith("/") and use this variable to decide if you prepend the default or not!

  • Related