Java Code for providing the change directory functionality

Assuming that the path separator is ‘/’, write a code to provide the change directory functionality. For example, new Path(“/a/b/c/d”).cd(“../../x”).getPath() should return “/a/b/x”.

import java.util.Stack;

public class Path {
private String path;

public Path(String path) {
this.path = path;
}

public String getPath() {
return path;
}

public Path cd(String newPath) {
String[] folders = path.split("/");

Stack stack = new Stack();
for (int i = 0; i < folders.length; i++) {
stack.push(folders[i]);
}

String[] newFolders = newPath.split("/");

int jumps = 0;
for (int i = 0; i < newFolders.length; i++) {
if (newFolders[i].equals("..")) {
jumps ++;
stack.pop();
} else {
break;
}
}

for (int i = jumps; i < newFolders.length; i++) {
stack.push(newFolders[i]);
}

String path2 = "";
Stack stack2 = new Stack();
while (!stack.isEmpty()) {
stack2.push(stack.pop());
}
while (!stack2.isEmpty()) {
String s = stack2.pop();
if (!s.equals("")) {
path2 += "/"+s;;
}
}
return new Path(path2);
}

public static void main(String[] args) {
Path path = new Path("/a/b/c/d");
System.out.println(path.cd("../x").getPath());
System.out.println(path.cd("../../x").getPath());
System.out.println(path.cd("../y/x").getPath());
System.out.println(path.cd("../x/x/x").getPath());
}
}

The result would be:
/a/b/c/x
/a/b/x
/a/b/y/x
/a/b/y/x/x/x

Leave a Reply

Your email address will not be published. Required fields are marked *