We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all,
I would like to return the number of folders in a specific path. Say I have a 'masks' folder in the data folder. This 'masks' folder can itself contain any number of folders and I need the program to respond to that number. How can I retrieve this quantity of folders as an int?
Answers
Almost a classical, with a twist, though.
You should take a look at the File Java class. It has everything you need.
Well, you also need to call dataFile("") to get the File object corresponding to the data folder.
Basically, you need listFiles() to get a list of the files (including folders) in the data folder, then isDirectory() to distinguish folders from plain files, then iterate on the found folders to see if they contain folders too, etc.
Thanks a lot! For anyone as noob as me, here's the small method I came up with.
Alternative version using FileFilter + listFiles() in order to recursively get a folders-only List: :bz
Good idea to use a filter, I should have remembered this... :-) It cuts down the code.
Moxl, your code is OK if you don't have nested folders, otherwise, use GoToLoop's one.
Note that I suggested to use dataFile() instead of dataPath(), that would avoid to wrap the result in a File() constructor... Idem for listFiles() instead of list().
I didn't know about dataFile("") which returns a File instead of a String as dataPath("") does! *-:)
Although it's somewhat useless, b/c Processing's IO functions accepts String references only! :(
I wish the devs would write overloaded File versions for all of them too! :-<
Actually, his only got folders inside "/data/". If there are any deeper subfolders within them, they're ignored.
Nonetheless, I did a shorter version of his using dataFile("") + listFiles() w/o any FileFilter: B-)
"it's somewhat useless"
Not if you need to do pure File operations as we describe above!
Doing
new File(dataPath(""));
actually invokes dataFile(), then extract the path out of it, to wrap it again in a new object..."his only got folders inside "/data/". If there are any deeper subfolders within them, they're ignored."
It thought that's what I wrote and what you quoted? Is my English so bad?
Wow thanks for all the development in replies. I'll try to wrap my head around this when I get the chance.