I have been stuck on this error for too long.
My approach is as follows. For built-in commands, I check if redirection is present or not and create the redirect file if it doesn’t exist.
But the problem is coming in external commands like ls
Here, my approach is to first find the relative path to the current directory, resolve it, and then normalize it to obtain the final path. I then check if its parent directories are present; if not, I create them. Then redirect to the file.
But it’s not working. Can you help me see where I have gone wrong.
You are concatenating this “user.dir” with the redirect, so you end up with a non-sense path. If you are in /a/b and the redirect is >/x/y/z you use Path.of to get /a/b/x/y/z.
Well if you get a relative path then you should use that relatively, and if you don’t you should the absolute. On POSIX/Linux you could possible try and see if there is a leading /. But I don’t even bother and instead delegate it to opensystem function:
Ah cool.
Thanks, but I found my error, and it was a silly one.
When I parsed my redirection string, there were two errors: first, that it started with an extra space, and second, when passed with quotes, it also included quotes, causing a problem in resolving the path.
The logic of resolving with the current directory is fine. only thing wrong was the way i was resolving that was using string, instead have to do with Path object only.
Besides the parsing error, the logic to get the redirect path when I looked was: Path file = Path.of(curDir.toString() , redir).normalize(); and when I tried Path.of(“/a/b”, “/x/y”) I got /a/b/x/y.You changed that to Path file = curDir.resolve(redir).normalize();.
Beware though Path.resolve(path) says: Where the given path has a root component then resolution is highly implementation dependent and therefore unspecified. Nvm, they fixed that somewhere between Java 8 and 21: If the other parameter is an absolute path then this method trivially returns other