Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - File exists and IS directory, but listFiles() returns null

The documentation for File.listFiles() suggests that null will ONLY be returned in the case that the file calling it is not a directory.

I have the following:

String dir = "/storage/emulated/0";
File f = new File(dir);
Log.v("Files",f.exists()+"");
Log.v("Files",f.isDirectory()+"");
Log.v("Files",f.listFiles()+"");

The log reads:

true
true
null

For some reason, listFiles() is returning null even though the File is recognized as a valid directory. I'm not super familiar with Android file hierarchy behavior, so I would guess the problem lies in there.

For reference, I'm debugging on my Moto X, and results are the same whether the phone is plugged in to my computer or not - so I don't think it has to do with mounting when plugged in.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For those with this problem, add this to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Problem solved :D

EDIT: If this does not work just make sure if path is correct


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...