Sandeep
Sandeep

Reputation: 1401

Creating an absolute path

The Java Paths class has this useful method for creating a Path object:

Path path = Paths.get("a", "b", "c", "d", "e.txt");

However, with this approach the resultant path is relative to the invoking directory. What is the best platform-independent way to get an absolute path (one which transparently incorporates both the Windows \ and the Unix / conventions)?

Upvotes: 0

Views: 570

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102795

If you have a Path object that needs to be an absolute path instead, you can just invoke toAbsolutePath() on it; note that path objects know what the platform separator is; it is already platform independent, there's no need to manually convert any slashes.

If you mean: I have a bunch of strings and I want on unix to obtain a path representing /a/b/c/d/e.txt but on windows to obtain a path representing C:\a\b\c\d\e.txt that's a problem. Because C: is not actually something you just get to assume.

Your question is then unanswerable: Turns out that if you want to be fully platform independent, there is no such notion as 'the root directory'. On windows, one can only speak of 'a root directory', and there are as many as file systems hooked up to a drive letter, and that too is a tricky abstraction, because really windows works with a \\drive-identifier\path model.

Something you may want to investigate:

for (Path p : FileSystems.getDefault().getRootDirectories()) {
    System.out.println("Found a root: " + p);
}

You could for example go with 'just go off of the first root, whatever it is':


Path root = FileSystems.getDefault().getRootDirectories().iterator().next();
Path p = root.resolve(Paths.get("a", "b", "c", "d", "e.txt"));
System.out.println(p);

Whether that is the root you intended (presumably, C:) - that'll depend on quite a few factors.

The best thing to do is to forget about having separate strings. If you are taking user input representing an absolute path, take one, single string. A user on windows is bound to type something like: C:\Users\Sandeep\hello.txt, and Paths.get() has no problem with that input at all. A user on mac might type /Users/Sandeep/hello.txt and this too works just fine if you feed it to Path, and operations from there on out are entirely platform independent already.

Upvotes: 1

Related Questions