Java Random File getRandomFile(String dir)

Here you can find the source of getRandomFile(String dir)

Description

Get a random file from a directory.

License

Open Source License

Parameter

Parameter Description
dir the directory to search in.

Return

a file name full path.

Declaration

public static String getRandomFile(String dir) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *
 * File:    Utils.java//from   w ww .j  av a  2  s .co  m
 * Project: SetiQuestInfo
 * Authors: Jon Richards - The SETI Institute
 *
 * Copyright 2012 The SETI Institute
 *
 * SetiQuestInfo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SetiQuestInfo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SetiQuestInfo.  If not, see<http://www.gnu.org/licenses/>.
 *
 * Implementers of this code are requested to include the caption
 * "Licensed through SETI" with a link to setiQuest.org.
 *
 * For alternate licensing arrangements, please contact
 * The SETI Institute at www.seti.org or setiquest.org. 
 *
 *******************************************************************************/

import java.io.*;

import java.util.*;

public class Main {
    /**
     * Get a random file from a directory.
     * @param dir the directory to search in.
     * @return a file name full path.
     */
    public static String getRandomFile(String dir) {
        File directory = new File(dir);
        int count = 0;
        String randomFileName = "";

        if (directory.exists()) {
            File[] listFiles = directory.listFiles();
            int numFiles = listFiles.length;
            Random rand = new Random(System.currentTimeMillis());
            int index = rand.nextInt(numFiles - 1);
            randomFileName = listFiles[index].getAbsolutePath();

        }

        return randomFileName;
    }
}

Related

  1. getRandomFile(String testName)
  2. getRandomFilename(String filePath)
  3. getRandomFilename(String prefix, String sufix)
  4. getRandomFilenameInDirectory(File rootFolder)