NIO2 Path Symbols Java - java

If I created a two paths such as:
Path path3 = Paths.get("E:\\data");
Path path4 = Paths.get("E:\\user\\home");
And then make a new Path(relativePath) by using the relativize() method on the two paths, creating: "..\user\home" does the path symbol(..) in this case refer to "data" or does it just indicate a relative path?
Path relativePath = path3.relativize(path4);
// ..\user\home <- output
So my Question is, what does the Path symbol (..) represent?

The relativize method needs two inputs but doesn't "secretly" encode the base path into it's output, so your relativePath has to be applied to another base path to actually access a path on disk.
But you can apply it to a different base path, e.g. if you want to sync two folder structures below two different base paths.
tl;dr: it just indicates a relative path.
But take care with your path separator: if you hardcode that into your path strings like in your example, it will fail on other systems. Better split up the individual parts in extra strings like this:
Path path4 = Paths.get("E:", "user", "home");

Related

Is there a cleaner way to represent a parent path from a filesystem URL?

I have an source path which I receive as a filesystem URL from which I want to resolve to an absolute path two parents above; the final type as a Path object is desired. To do this I have to convert it to a URI, then to a Path, and then call getParent() on it twice.
Is there a cleaner way to perform this such that I can perform some transformation on either the URL, URI, or Path with a relative string ../..? I've always found that multiple invocations of getParent() to transverse a path to be less intuitive to read at a glance than to provide a relative path with ../, etc.
// Example file system path as a URL
URL u = new URL("file:///a/b/c");
// Must convert to URI and then call 'getParent()' twice
Path p = Paths.get(u.toURI()).getParent().getParent();
If you do not need the URL variable anywhere else, then you can skip the conversion like so:
p = Paths.get(new URI("file:///a/b/c")).getParent().getParent();
Now, this next part could be seen as more complicated than it needs to be, but if you just need the folder name, you could do a .getName(0) instead of the two .getParent()'s. However, this does not include the root when you print it out, and it might not meet your needs.
I hope this helps.

How to program relative path from string in Java

I have the following problem. I am writing a program that imitates Windows Command prompt. For example user enters: cd C:\\Intel and in my code I solve it like this:
setCurrentPath(Paths.get(string));
where setCurrentPath is a method which sets the current path to the one which is entered (string). My problem is that, how can I set new path if the entered path is relative. For example, if I am currently in C:\\Intel and user wants to go to C:\\Intel\\Logs and enters: cd Logs (instead of C:\\Intel\\Logs). I suppose there are some methods build in Java which can help me out but I am learning Java only a few months so I am unaware of them. Be aware that I threat path as a string.
You could test if path from user is absolute or not and based on result either set it directly, or use Path.resolve.
DEMO:
Path currentPath = Paths.get("C:\\projects\\project1");
String pathFromUser = "..\\project2";
Path userPath = Paths.get(pathFromUser);
if (userPath.isAbsolute()){
currentPath = userPath;
}else{//is relative
currentPath = currentPath.resolve(userPath).normalize();
}
System.out.println(currentPath);
Output: C:\projects\project2
Use the isAbsolute() method to check the input and then use the resolvePath if the isAbsolute() method returns false.
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#isAbsolute()
The reason why you have to check if the path is absolute first is described below for the resolve method:
Path resolve(Path other)
Resolve the given path against this path. If the other parameter is an
absolute path then this method trivially returns other. If other is an
empty path then this method trivially returns this path. Otherwise
this method considers this path to be a directory and resolves the
given path against this path. In the simplest case, the given path
does not have a root component, in which case this method joins the
given path to this path and returns a resulting path that ends with
the given path. Where the given path has a root component then
resolution is highly implementation dependent and therefore
unspecified.
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#resolve(java.nio.file.Path)

Why does Path class allow file within a file?

I'm playing around with the NIO Path stuff, and came across this quesion:
What will the following code fragment print?
Path p1 = Paths.get("\\personal\\readme.txt");
Path p2 = Paths.get("\\index.html");
Path p3 = p1.relativize(p2);
System.out.println(p3);
The answer is
..\..\index.html
But this would make the entire Path:
\personal\readme.txt\index.html
This looks like nonsense to me, as you can't put a file within a file like this. Can you?
If readme.txt were a directory instead of a file, I would be perfectly OK with this, but I'm very confused as to why it allows a filepath like this to exist?
Or is there some weird way that you can actually do this?
Both ISOs and Zip files (therefore JAR/WAR/XUL/CHM...) represent files that can contain a folder structure of files. These files can be handled either as a file, or as a folder; both are legitimate uses for them. Therefore, this would be semantically meaningful:
Path p1 = Paths.get("\\personal\\photos.zip");
Path p2 = Paths.get("\\family\\me.png");
Path p3 = p1.relativize(p2);
System.out.println(p3);"
While I am not aware of any implementations in Java that behave this way, it is a semantic used in XUL and Windows Explorer.
The result is ..\..\index.html
From the javadoc:
This method attempts to construct a relative path that when resolved
against this path, yields a path that locates the same file as the
given path. For example, on UNIX, if this path is "/a/b" and the given
path is "/a/b/c/d" then the resulting relative path would be "c/d".
Where this path and the given path do not have a root component, then
a relative path can be constructed.
This means that you would have to go up two folders from this path to reach a path from which you can reach your given path, index.html.
Remember, these are all paths, not actual files/file descriptors.
Path p1 = Paths.get("\\personal\\readme.txt");
Path p2 = Paths.get("\\personal\\index.html");
Path p3 = p1.relativize(p2);
System.out.println(p3);
prints ..\index.html, meaning from \\personal\\readme.txt, go up one and then access index.html.

java.nio.Path relativize between Paths does assumptions, which I cannot check

I am using the new Path object of java 7 and I am running into an issue.
I have a file storage system with a base directory and I create my own relative path. In the end I want to store just this relative path somewhere. I am running into a problem with Path.relativize though.
I have two usecases.
1.
Path baseDir = Paths.get("uploads");
Path filename = Paths.get("uploads/image/test.png")
return baseDir.relativize(filename);
This returns a Path image/test.png, which is perfect.
However, usecase 2:
Path baseDir = Paths.get("uploads");
Path filename = Paths.get("image/test.png")
return baseDir.relativize(filename);
returns ../image/test.png. I just want it to return "image/test.png"
In the Path tutorial it says
In the absence of any other information, it is assumed that 2 Paths are siblings
What I want is to be able to detect that this is the case. In this case, I want to just return the filename and ignore the baseDir.
I currently solve it like this, but I was hoping there was a better way:
Path rootEnding = getRootDirectory().getName(getRootDirectory().getNameCount() - 1);
for (Path part : path) {
if (part.equals(rootEnding)) {
return getRootDirectory().relativize(path);
}
}
return path;
So my question is, is there any better way of checking this?
Try adding a normalize() after relativize(). It seems to intended to do exactly this (remove unnecessary .. and . ). Don't miss the caution about symlinks in the javadoc.
This isn't 100% equivalent to what you wrote above, but I think it does what you want. Basically, let baseDir be a relative path. Pretend that whatever baseDir is relative to is the root of the file system. Then allow filename to be either relative or absolute from this "simulated root".
What about:
if (filename.startsWith(baseDir)) {
filename = baseDir.relativize(filename);
}

How do I create a File from a string that may represent an absolute or a relative path?

I have a directory pointed to by a File object called baseDir in which I keep most of my files.
I have a String f which may contain a relative filename, like "data.gz", or an absolute filename like "/mnt/data.gz" (its specified in a config file).
In the event that f is relative, it should be assumed that the file specified is within baseDir, but if it is absolute then it should be treated accordingly.
How do I create a File object that points to the file represented by f?
I can think of hacky solutions to this (eg. if (f.startsWith("/")) ... but I'm hoping there is a "right way" to do this.
Oh, I tried using the File(File, String) constructor for the File object, but it doesn't do what I need it to do.
Use File.isAbsolute(x)
http://download.oracle.com/javase/6/docs/api/java/io/File.html#isAbsolute%28%29
If this returns false, prepend your basedir.
You can try the following:
File file = new File(f);
if(file.isAbsolute())
...
Be careful that the definition of absolute path is system dependent!

Categories

Resources