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)
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 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.
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);
}
I'm a bit confused with all these new File I/O classes in JDK7.
Let's say, I have a Path and want to rename the file it represents. How do I specify the new name, when again a Path is expected?
Path p = /* path to /home/me/file123 */;
Path name = p.getName(); /* gives me file123 */
name.moveTo(/* what now? */); /* how to rename file123 to file456? */
NOTE: Why do I need JDK7? Handling of symbolic links!
Problem is: I have to do it with files whose names and locations are known at runtime. So, what I need, is a safe method (without exceptional side-effects) to create a new name-Path of some old name-Path.
Path newName(Path oldName, String newNameString){
/* magic */
}
In JDK7, Files.move() provides a short and concise syntax for renaming files:
Path newName(Path oldName, String newNameString) {
return Files.move(oldName, oldName.resolveSibling(newNameString));
}
First we're getting the Path to the new file name using Path.resolveSibling()
and the we use Files.move() to do the actual renaming.
You have a path string and you need to create a Path instance. You can do this with the getPath method or resolve. Here's one way:
Path dir = oldFile.getParent();
Path fn = oldFile.getFileSystem().getPath(newNameString);
Path target = (dir == null) ? fn : dir.resolve(fn);
oldFile.moveTo(target);
Note that it checks if parent is null (looks like your solution don't do that).
OK, after trying everything out, it seems I found the right method:
// my helper method
Path newName(Path oldFile, String newNameString){
// the magic is done by Path.resolve(...)
return oldFile.getParent().resolve(newNameString);
}
// so, renaming is done by:
oldPath.moveTo(newName(oldFile, "newName"));
If you take a look at Apache Commons IO there's a class called FileNameUtils. This does a ton of stuff wrt. file path names and will (amongst other things) reliably split up path names etc. I think that should get you a long way towards what you want.
If the destination path is identical to the source path except for the name of the file, it will be renamed rather than moved.
So for your example, the moveto path should be
/home/me/file456
If you can't get Java to do what you want with Unix I recommend Python scripts (run by your Java program). Python has get support for Unix scripting and it's not Perl :) This might sound inelegant to you but really in a larger program you'll benefit from using the right tool for the job.