I know that all files and directories and all subdirectories under a drive can be deleted programatically using recurssion. Is it possible to do the same non-recursively? If yes, please give the sample code or if not possible state the reason?
I faced this question in an interview and I said its not possible to delete non-recursively? Am I currect?
The File class only allows you to delete empty dirs, so yes: this is typically done by recursively visiting lower directories and emptying them.
But you could also start a native operation system command from java that removes a dir that is not empty and its subdirs (e.g. rm -fr in unix). That would be a non-recursive solution.
Rob Prime wrote:Why don't you want to use recursion? For any tree-like structure, including files and folders, recursion is the obvious and easiest mechanism.
Agreed. Most of the time recursion is avoided (assuming that its the best option) because the algorithm doesn't have an upper capacity in memory usage. In this case, I highly doubt you will encounter a case where the directory structure is so deep that you'll run out of heap.... And it's also the best option too.
Sorry... didn't read the question correctly. It's an interview question. Anyway....
Having an example on how to delete a directory, in a non-recursive manner, misses the point. Remember back to your old algorithms class? when you first learned about recursion? Remember all that work that you did prior to using recursion, with stack based data structures, to do stuff, that became really easy once you added recursion to your arsenal?
That's the point of the interview question. The interview was likely testing you to see if you understood the basics of recursion, which includes an understanding on how to do recursion, without the language making it so easy for you to do it -- to simulate it using data structures.