phlip9
phlip9

Reputation: 48

Generate Random File Paths Java

Is there some way to randomly generate an arbitrary file path in Java?

What I've been thinking is that perhaps I could either pick one out of a pre-selected array, but that wouldn't be very random. Or I could start at C:\, pick a random number from 0 to the number of folders; if it's 0, I choose C:\, else I pick the folder corresponding to the random number. Rinse and repeat until it hits 0.

I don't feel like these are the best solutions, so any help would be appreciated.

Upvotes: 1

Views: 3556

Answers (3)

Stephen Denne
Stephen Denne

Reputation: 37007

By mentioning 'best' you could be meaning that you wish for folder selection to be fair in some way, like perhaps based on the number or size of files inside it. You can only do that if you know the complete details to start with. Otherwise, I'd go with your recursive selection at each level suggestion.

Upvotes: 0

aioobe
aioobe

Reputation: 420971

Here's an example to get you started:

import java.io.File;
import java.util.*;

class Test {

    private static Random r = new Random();

    public static File getRandomFileIn(File f) {

        File[] subs = f.listFiles();

        if (f.isFile() || f.list().length == 0)
            return f;

        List<File> subDirs = new ArrayList<File>(Arrays.asList(subs));

        Iterator<File> files = subDirs.iterator();
        while (files.hasNext())
            if (!files.next().isDirectory())
                files.remove();

        while (!subDirs.isEmpty()) {
            File rndSubDir = subDirs.get(r.nextInt(subDirs.size()));
            File rndSubFile = getRandomFileIn(rndSubDir);
            if (rndSubFile != null)
                return rndSubFile;
            subDirs.remove(rndSubDir);
        }

        return null;
    }

    public static void main(String[] args) {

        File[] roots = File.listRoots();
        File rndFile = getRandomFileIn(roots[r.nextInt(roots.length)]);

        System.out.println(rndFile);
    }
}

Was actually quite fun to see some random files... I didn't know about roughly 90 % of them :-)

Upvotes: 1

Ben
Ben

Reputation: 13625

Create a MD5 Hash and use it as directory

Upvotes: 0

Related Questions