On 01/26/2013 05:14 AM, Wojtek wrote:
Using:
int max = 10;
int count = 0;
for (File thisFile : aDir.listFiles())
{
doSomething(thisFile);
if ( ++count >= max )
break;
}
gives me the first ten files in aDir. But if aDir contains 30K files,
then the listFiles() will run for a long time as it builds an array for
the 30K files.
Is there a way to have Java only get the first "max" files?
One way of doing it, which you can find by Googling but should occur to
you if you read the File Javadocs carefully, is below.
I've run this in an IDE with the working directory set to where I
touched a few hundred files.
The files returned will not be in any order; OTOH you didn't indicate
what you meant by "first".
AHS
-------------------------
package org.ahs.files;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
public class ShortFileList {
final int maxFiles = 30;