ChrisEthanFox ChrisEthanFox - 2 months ago 17
Java Question

Pick a random file from a directory in Java

I would like to pick a random file from any directory I want. such as
C:\Users\Josh\Pictures\[randomFile]

I have no code to show I just would like to know how I would come by doing that.

What I am fully doing is using a class to change the background of my desktop, and now I want to add a random file to it so when it refreshes the background will be different and I wont have to stop the running code to manually change the name of the file in the path. If you are wondering heres what it looks like

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class BackgroundTest {

final static File dir = new File("C:\\Users\\Kevin\\Pictures\\Pyimgur\\");
static int size = 10;
static String [] fileArray = new String[size];





public static void main(String[] args) {
File[] files = dir.listFiles();
for(int i =0; i<size;i++){
int idz = (int)(Math.random()*size);
fileArray[i]=files[idz].getName();

}

for(String x: fileArray){
System.out.print(x);
}

String path = "C:\\Users\\Kevin\\Pictures\\Pyimgur\\";
String picture = "picture.jpg";
//System.out.print(fileArray[0]);

SPI.INSTANCE.SystemParametersInfo(
new UINT_PTR(SPI.SPI_SETDESKWALLPAPER),
new UINT_PTR(0),
path + picture,
new UINT_PTR(SPI.SPIF_UPDATEINIFILE | SPI.SPIF_SENDWININICHANGE));
}

public interface SPI extends StdCallLibrary {

//from MSDN article
long SPI_SETDESKWALLPAPER = 20;
long SPIF_UPDATEINIFILE = 0x01;
long SPIF_SENDWININICHANGE = 0x02;

SPI INSTANCE = (SPI) Native.loadLibrary("user32", SPI.class, new HashMap<Object, Object>() {
{
put(OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
put(OPTION_FUNCTION_MAPPER, W32APIFunctionMapper.UNICODE);
}
});

boolean SystemParametersInfo(
UINT_PTR uiAction,
UINT_PTR uiParam,
String pvParam,
UINT_PTR fWinIni
);
}
}

Answer
  1. Create an array of the files within the given directory using File.listFiles().
  2. Select a file based on a random index from this array.
    That can be done with an instance of the Random class, using Random.nextInt(int bound), where bound, in this case, is the amount of files in the array, thus the array's length.

Example:

File[] files = dir.listFiles();

Random rand = new Random();

File file = files[rand.nextInt(files.length)];
Comments