Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!us.feeder.erje.net!news2.arglkargh.de!news.swapon.de!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: The first 10 files Date: Sat, 26 Jan 2013 16:00:42 -0700 Organization: by the dead and drowsy fire Lines: 28 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx04.eternal-september.org; posting-host="3c5d835c9a0219e1946f4dd3740c28b0"; logging-data="7723"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/ZZgz+WpdnsMo6z6Q/F9tO" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) Cancel-Lock: sha1:g+/95fUnvFsyDaV31m4fmfGehBM= sha1:c2rRkLIF0duNVLTe/MDvdiXPA9w= Xref: csiph.com comp.lang.java.programmer:21758 Wojtek writes: > 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? As Roedy says, in pure Java there's no way to avoid reading the entire directory, whether it builds the entire array or not. And if you want them in any particular order it's necessary to read them all and sort them anyway. -- Jim Janney