Normally, a path ignores all the . (this directory) it contains. So, c:\\personal\\.\\photos\\readme.txt and c:\\personal\\photos\\readme.txt should give identical results for different operations, but in the following code, the normalized path gives a different result. Can anyone explain the reason for this?
Path p1 = Paths.get("c:\\personal\\.\\photos\\readme.txt");
Path p2 = Paths.get("c:\\personal\\index.html");
Path p3 = p1.relativize(p2);
System.out.println(p3);
p1 = p1.normalize();
p2 = Paths.get("c:\\personal\\index.html");
p3 = p1.relativize(p2);
System.out.println(p3);
Output:
..\..\..\index.html
..\..\index.html
Path class itself does not ignore \\. by default. It happens when you explicitly ask through normalize(). Here in oracle documentation on path's relativize method http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#relativize(java.nio.file.Path) For example, if this path is "/a/b" and the given path is "/a/x" then the resulting relative path may be "../x".
So the answer might be that, path does not by default discards \\.. Which along with oracle documentation results the output you see.
Related
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");
I've now read numerous articles on the use of Java somePath.resolve( someOtherPath ) but I can't find a precise definition, with helpful examples, of what exactly "resolving" a Path means. Everyone seems to assume you know.
Can someone define it non-circularly? Or point me to a (non-circular) explainer?
The answer to this is defined in the documentation, which does a great job of indicating what the method does.
Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the resolve method. For example, suppose that the name separator is "/" and a path represents "foo/bar", then invoking this method with the path string "gus" will result in the Path "foo/bar/gus".
In other words, if the path C:/Program Files/Foo/ is the current Path and Bar exists in Foo, you could do the following:
Path parent = Paths.get("C:", "Program Files", "Foo");
Path child = parent.resolve("Bar");
Jason's answer is complete, but on the off chance you're looking for an even simpler answer/example..
I would say the "resolve" method that you specificaly referred to (which starts at somePath) starts at a certain Path, somePath, and then tells you what would happen if you choose to go to someOtherPath but specifically starting at somePath.
So if you had a directory structure on a PC, for example, like this:
C:
- FolderA
- Folder1
- FolderB
- Folder1
If you resolved someOtherPath as "Folder1", then it would depend where you started...
If your somePath was "/FolderA" then you'd end up at "C:/FolderA/Folder1"
If your somePath was "/FolderB" then you'd end up at "C:/FolderB/Folder1"
If your somePath was "/" (the root), then you'd have an invalid path...
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)
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.
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);
}