Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Knute Johnson Newsgroups: comp.lang.java.programmer Subject: Re: The first 10 files Date: Sat, 26 Jan 2013 18:37:09 -0800 Organization: A noiseless patient Spider Lines: 75 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-15; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 27 Jan 2013 02:37:10 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="aba33539224e5c782fe0c4053f7756fd"; logging-data="10731"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18YgRAlpzfcBbE5A7wqW/vK" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130107 Thunderbird/17.0.2 In-Reply-To: Cancel-Lock: sha1:/QxPsQScZ4JI6QAAjsZswZnOIS4= Xref: csiph.com comp.lang.java.programmer:21772 On 1/26/2013 1: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? > import java.io.*; import java.nio.*; import java.nio.file.*; public class FileSystemsTest { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); Path dir = FileSystems.getDefault().getPath("."); int i=10; DirectoryStream stream = Files.newDirectoryStream(dir); for (Path path : stream) { System.out.println(path.getFileName()); if (--i <= 0) break; } long stop = System.currentTimeMillis(); System.out.println(stop - start); } } 300003 files in the directory, almost 1.7GB of files, Windows XP, Java 7 and it takes 16 ms to run. Somebody else should try this out on their computer to see if it works as fast. . . . 01/26/2013 05:46 PM 58,890 9998.txt 01/26/2013 05:46 PM 58,890 9999.txt 01/26/2013 06:31 PM 1,316 FileSystemsTest.class 01/26/2013 06:29 PM 636 FileSystemsTest.java 01/26/2013 05:44 PM 650 MakeFiles.java 30003 File(s) 1,766,702,602 bytes 2 Dir(s) 49,387,085,824 bytes free C:\Documents and Settings\Knute Johnson\bigdirectory>java FileSystemsTest 0.txt 1.txt 10.txt 100.txt 1000.txt 10000.txt 10001.txt 10002.txt 10003.txt 10004.txt 16 C:\Documents and Settings\Knute Johnson\bigdirectory> -- Knute Johnson