DirectoryStream on Windows

Alan Bateman Alan.Bateman at oracle.com
Wed Nov 23 07:29:56 PST 2011


On 23/11/2011 14:53, Matthias Bergk wrote:
>
> Dear all,
>
> I examined the file attributes that come with a directory stream on 
> Windows.
>
> I found that the returned Path objects are of the class 
> WindowsPath$WindowsPathWithAttributes.
>
> But how to get at those attributes? The following code is taken from 
> JDK sample code:
>
> try( DirectoryStream<Path> stream = Files./newDirectoryStream/(folder) )
>
> {
>
> for( Path entry : stream )
>
> {
>
> BasicFileAttributeView v =
>
> Files./getFileAttributeView/(entry,BasicFileAttributeView.class);
>
> BasicFileAttributes a = v.readAttributes();
>
> System./out/.println( entry+" "+a.size() );
>
> }
>
> }
>
> Unfortunately this code does not benefit from the file attributes that 
> are available in the entries.
>
> Rather, it reads them anew from the system.
>
> Using "reflection" it is possible to get at the attributes contained 
> in the entries:
>
> try( DirectoryStream<Path> stream = Files./newDirectoryStream/(folder) )
>
> {
>
> for( Path entry : stream )
>
> {
>
> Field fRef = entry.getClass().getDeclaredField("ref");
>
> if( !fRef.isAccessible() )
>
> fRef.setAccessible(true);
>
> WeakReference<BasicFileAttributes> ra =
>
> (WeakReference<BasicFileAttributes>) fRef.get(entry);
>
> BasicFileAttributes a = ra.get();
>
> System./out/.println( entry+" "+a.size() );
>
> }
>
> }
>
> This code is considerably faster if the folder is on a network and 
> contains many files.
>
> Of course, I would prefer to read the attributes without reflection in 
> the intended way.
>
>
The first example is the recommended way to do this but would be nicer 
if we did:

BasicFileAttributes attrs = Files.readAttributes(entry, 
BasicFileAttributes.class);

On the caching then the JDK can't know in advance that you will will 
invoke readAttributes on each file in the directory.  The only place in 
the API where it is known is Files.walkFileTree so you should fine that 
will give you the performance you are looking for.

-Alan





-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.openjdk.java.net/pipermail/nio-dev/attachments/20111123/e7455aec/attachment-0001.html 


More information about the nio-dev mailing list