随机文件访问Java

时间:2013-12-24 06:28:37

标签: java image

我知道有一种方法可以从目录中选择一个随机文件,但我不知道它是如何用Java编码的。我有伪代码。我问的是,如果我能在正确的方向上轻推一下。我的伪代码如下:

dir = "directory";
String[] files = dir.listfiles();
String next = rand.nextInt(files.length);
Image img = next;

我想这样做的原因是因为我有一个图像列表,我想要随机播放。

4 个答案:

答案 0 :(得分:4)

您的伪代码看起来很好,您可以递归获取所有名称,将名称存储在ArrayList中,并从ArrayList中随机检索名称,如下所示:

static ArrayList<String> files = new ArrayList<String>();

public static void main(String[] args) {
    File dir = new File(".");
    getFileNames(dir);
    Random rand = new Random();
    String next = files.get(rand.nextInt(files.size()));
}

private static void getFileNames(File curDir) {
    File[] filesList = curDir.listFiles();
    for (File f : filesList) {
        if (f.isDirectory())
            getFileNames(f);
        if (f.isFile()) {
            files.add(f.getName());
        }
    }
}

答案 1 :(得分:1)

你似乎走在了正确的轨道上。唯一的问题是listFiles()会返回File[]而不是String[]

也许尝试这样的事情

File file = new File(filename);
File[] files = new File[0];     // initialize
if (file.isDirectory()){
    files = file.listFiles();   // populate
}
int fileIndex = new Random().nextInt(files.length);      // get random index
Image img = new ImageIcon(files[fileIndex]).getImage();  // create image

虽然上述方法可行,但建议使用URL来嵌入资源而不是文件。像这样的东西

String[] filenames = file.list();    // list returns String
int fileIndex = new Random().nextInt(filenames.length); 
Image img = null;
java.net.URL url = MyClass.class.getResource(filenames[fileIndex]);
if (url != null){
    img = new ImageIcon(url).getImage();
} else {
    img = null;
}

使用class.gerResource()时。将在类文件的位置搜索该文件。您也可以稍微改变路径,例如,如果您想要这样的文件结构

ProjectRoot
          bin
             MyClass.class
             images
                  image1.png
                  image2.png
          src

然后你可以使用这段代码

java.net.URL url = MyClass.class.getResource("images/" + filenames[fileIndex]);

答案 2 :(得分:0)

以下是我将如何实现您的伪代码

private static final Random random = new Random(0x20131224 ^ // A seed value
      System.currentTimeMillis());                           // and more seed value(s).
public static File getRandomFile(String filePath) {
  File f = new File(filePath);                               // Do we have a directory?
  if (f == null || ! f.isDirectory()) {
    return f;
  }
  File[] files = f.listFiles();
  List<File> al = new ArrayList<File>();
  for (File file : files) {
    if (file != null && file.isFile() && file.canRead()) {   // Make sure it's a file.
      al.add(file);
    }
  }
  return al.get(random.nextInt(al.size()));                  // Get a random file.
}

答案 3 :(得分:0)

File filedir=new File("C:\\Users\\ramaraju\\Desktop\\japan02-12\\");
File[] files=filedir.listFiles();

Random generator = new Random();
int Low = 0;
int High = files.length;
int R = generator.nextInt(High-Low) + Low;
System.out.println(R);
for (int i = 0; i < files.length; i++) {
    if(i==R)
    {
        System.out.println(files[i].getName());
    }
}
相关问题