I'm trying to retrieve directory contents in a swing application. I learned that JFileChooser can be used to retrieve contents of a specific directory (say /X/), but only till one level down (x/a.txt or x/b.txt and not x/y/z.txt). What if I want to get all the contents of the X, Y and even other directories internal contained in deeper layers of the other folders(y/as/sd/). Do we have to run any recursive loop to get such contents, or do we have any utility to do this. Hope my Question made some sense. Need suggestion!
Asked
Active
Viewed 108 times
0
-
Yes, it is not hard to get files recursively in a directory, and getting it has nothing to do with JFileChooser, but I'm not sure of your actual problem. Please tell us more about your ultimate goal, about what you want to do with this data. – Hovercraft Full Of Eels Feb 01 '14 at 04:54
-
Here is the code using java nio API http://stackoverflow.com/a/13539602/295765 – qza Feb 01 '14 at 05:27
1 Answers
2
Do we have to run any recursive loop to get such contents,..
Yes.
..or do we have any utility to do this.
You make it sound like getting the files recursively is difficult! It is really quite easy.
- Create a method that accepts a directory as argument.
- List the files.
- Check each file:
- If it is a file (as opposed to a directory), add it too an expandable list (e.g.
ArrayList<File>
). - If it is a directory, call the method again with that directory.
- If it is a file (as opposed to a directory), add it too an expandable list (e.g.
- Once this process has finished, the expandable list should contain all the files (that are not directories).

Andrew Thompson
- 168,117
- 40
- 217
- 433
-
1Or you could just [walk the file tree](http://docs.oracle.com/javase/tutorial/essential/io/walk.html) with Java 7's new nio...but where's the fun in that ;) +1 – MadProgrammer Feb 01 '14 at 05:42
-
@MadProgrammer Yeah.. I tend to lag one version behind the current major version when developing desktop apps. Though given the recent security scares and auto-update, I am questioning the wisdom of maintaining that stance.. – Andrew Thompson Feb 01 '14 at 05:51
-
1We're still actively developing under 6 without any consideration for 7 in the near future, about the only thing I get out of 7 right now is the diamond operator ;) – MadProgrammer Feb 01 '14 at 06:37