从Java目录中选择随机文件

从Java目录中选择随机文件

本文介绍了从Java目录中选择随机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我想要的任何目录中选择一个随机文件.如C:\ Users \ Josh \ Pictures \ [randomFile]

I would like to pick a random file from any directory I want. such asC:\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
    );
    }
}

推荐答案

  1. 使用File.listFiles()在给定目录中创建文件的array.
  2. 从此数组中基于随机索引选择文件.
    可以使用Random.nextInt(int bound)使用Random类的实例来完成,其中bound在这种情况下是array中的文件数量,即数组的长度.
  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)];

这篇关于从Java目录中选择随机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:20