问题
I'm trying to build a command line interpreter that implements "cd" command in linux. I don't know how the function that suppose to do that shoud work.
I know that this question has already been answered here: Changing the current working directory in Java?
But I'm new to Java and I read alot about this and still don't get how new File(parent, path)
would help me change my directory. Any help please?
回答1:
It won't help you change the directory; it is what is advised to use instead of changing the current working directory. The position of the designers of Java is that, if some part of your application needs a specific context directory other than the current working directory inherited from the underlying OS, this should be done by relying on the explicit two-argument File
constructor (and likewise for any other file-based APIs).
Note that this makes a lot of sense because the current working directory is effectively global state, and mutable global state is a well-knows Pandora's box of untraceable bugs.
回答2:
I used a global variable that holds the path of my current direction. cd
would just change it and all other commands use/modify it accordingly. Nothing simpler I guess.
来源:https://stackoverflow.com/questions/26631456/changing-the-current-directory-in-java-to-implement-cd-command-in-linux