MyNameIsNemo
MyNameIsNemo

Reputation: 71

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.

Upvotes: 0

Views: 334

Answers (2)

Pshemo
Pshemo

Reputation: 124235

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

Upvotes: 2

Snusmumrikken
Snusmumrikken

Reputation: 300

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)

Upvotes: 1

Related Questions