NullPointerException when using java.io.File

此生再无相见时 提交于 2019-11-28 14:29:34

File.listFiles() is not guaranteed to return a non-null value. This tends to occur (from my experience) because Java could see what looked like directory, but could not list it (Junctions come to mind)

Even the javadoc of

f.listFiles()

says... If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.

So i believe this is the culprit.

For the reason that MadProgrammer pointed out, add a null-check.

Replace:

for (int i = 0; i < files.length; i++) {

with

if(files != null)
    for (int i = 0; i < files.length; i++) {

I changed the drive to D (as I have no E drive) and the program completed successfully on my machine with this fix.

try "E:\\" for getting into the directory. I think it should work.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!