vendredi 31 août 2018

Get a random file from a random folder

I have a folder "testfiles" in my project directory, which contains a lot of others folders. Those folders all have names like "alice-g" (firstname and then first letter from lastname). Each of those folders contains some other folders, not always the same number. And in each of those last folders, i got a bunch of files, all named with number ("1.", "2.", "3." and so on).

What i want to do is going into this "testfiles" directory, randomly select a folder, get his name, then randomly select another folder in it and finally select a random file in this folder (and get his name).

I have found this post which say we can pick a random file from a folder this way:

File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];

This sound clear and easy to me. However, since all my files have "easy numbered names", i wonder if there is a way to do this without making list of all files (i can have thousand of files in a directory, dunno how efficient this will be then...). Is there any way to just get the number of files in a directory (without making this list of all files)? Then i will just have to select a random number between 1 and the amount of files and i can set the filename and select the file.

Second, this solve the problem of selecting a random file, but not of selecting a random directory (and get his name).

It may be important to say that i'm on Ubuntu 16.04? I've never worked with directories in java, so dunno if it's really relevant.




Aucun commentaire:

Enregistrer un commentaire