• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Get a random file out of a folder???

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How can I pick a random file out of a folder???
 
Ranch Hand
Posts: 15304
6
Mac OS X IntelliJ IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you look at the java.io.File API you'll notice that if the File is a directory then you can get a File[] array back of all the files in that directory. Take the size of the array and generate a random number from 0 to files.length. Then use that random number to grab that array index, files[randomNumber].
 
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Gregg Bolinger wrote:If you look at the java.io.File API you'll notice that if the File is a directory then you can get a File[] array back of all the files in that directory. Take the size of the array and generate a random number from 0 to files.length. Then use that random number to grab that array index, files[randomNumber].



@OP:
Note that although listFiles() returns an array of File's, this array also contains directories (if present). To get an array of the real files in that directory, you will need to provide a FileFilter and define you only want to get the File instances which return true for File.isFile().
 
Thang Pham
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot. I got it
 
reply
    Bookmark Topic Watch Topic
  • New Topic