Java display directory file list and delete directory function
Taking the D: \ a directory as an example, assume that the structure in the D: \ a directory is as follows:
4.1 example 1: list files in the entire directory (recursion)
Idea:
1. Traverse the directory D: \ a.
2. Traverse this subdirectory every time you traverse a directory in D: \ a. Therefore, you need to determine whether each traversed element is a directory.
The following is part of the code from normal code to recursive Code:
The repeated code part is encapsulated, so the recursive method is used to encapsulate the code and solve the problem of infinite recursion. The final code is as follows:
4.2 example 2: listing files (queues) in the entire directory
Idea:
1. Traverse the given directory. Put the traversed directory name into the collection.
2. Traverse each directory element in the collection, and add the traversed subdirectory to the collection. Finally, delete a directory from the collection every time the traversal ends.
3. In this way, as long as a directory is found, it will continue to traverse until a directory is completely traversed and start to traverse the next directory of the same level.
What needs to be considered is what kind of collection to use. Firstly, the directory elements in the set do not need to be sorted, and the subdirectory names in different directories may be repeated. Therefore, the list set is used instead of the set set set. Because the elements are frequently added and deleted, the LinkedList set is used instead of the ArrayList set. The most prominent feature of the LinkedList set is the FIFO queue.
Compared with recursive traversal, the advantage of using queue to traverse the directory is that the elements are placed in the container, and they are all in heap memory, which is not easy to overflow memory.
4.3 example 3: the tree structure displays the files in the entire directory (recursion)
Idea:
1. List the primary directory and files first.
2. If it is a directory, add a prefix symbol to form a tree. Then traverse the directory, where you need to traverse recursively.
The results are as follows:
4.4 delete the entire directory
summary
The above is the Java display directory file list and delete directory introduced by Xiaobian. I hope it will help you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!