× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

File.listFiles() does not work on Linux

Francis Galiegue
Mar 15, 2015
<p>That's one of the numerous problems with <code>File</code>; its <code>.listFiles()</code> method is unreliable.</p> <p>Try and use this instead:</p> <pre><code>final Path dir = Paths.get("path/to/directory"); final DirectoryStream&lt;Path&gt; dirStream = Files.newDirectoryStream(dir); // use the stream </code></pre> <p>If the fs entry is not a directory, you'll at least get a <code>NotDirectoryException</code>; if you don't have enough permissions, you'll get an <code>AccessDeniedException</code>; etc etc.</p> <p>Drop <code>File</code>. This is 2015, after all. And the new file API (aka JSR 203, aka NIO2) has been there since 2011!</p> <hr> <p>Since Java 8 you can also use <code>Files.list()</code>; DO NOTE however that you SHOULD use it in a try-with-resources block like this:</p> <pre><code>try ( final Stream&lt;Path&gt; stream = Files.list(thedir); ) { // use the stream } </code></pre> <p>It is a little known fact that <code>Stream</code> (well, <code>BaseStream</code> in fact) implements <code>AutoCloseable</code>!</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/28984430/File.listFiles()%20does%20not%20work%20on%20Linux/28984583">Stack Overflow</a>.</p>
comments powered by Disqus