为什么在目录上调用File.listFiles时可以返回null? [英] Why can File.listFiles return null when called on a directory?
问题描述
我正在创建一个Android应用,我想在目录中列出文件.我通过打电话来
I'm creating an Android app, and I want to list the files in a directory. I do this by calling
File[] files = path.listFiles(new CustomFileFilter());
path
是File
对象,它是通过调用创建的
path
is a File
object, which is created by calling
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
然后我尝试通过调用获取files
数组的长度
When I then try to get the length of the files
array by calling
int length = files.length;
此行给我一个NullPointerException
,因为files
为空.
This line gives me a NullPointerException
, because files
is null.
我通过调用检查了试图列出文件的path
是否存在
I have checked if the path
which I try to list the files in exists by calling
System.out.println("Path exists: " + path.exists());
当我运行该应用程序时,它会打印
And when I run the app, it prints
Path exists: true
在Android Studio控制台中,因此该目录存在.
in the Android Studio console, so the directory exists.
我还打印了路径名
/storage/emulated/0/Download
所以path
是目录,而不是文件.
So the path
is a directory, and not a file.
我不知道为什么要得到NullPointerException
,因为path
是目录.
I have no idea about why I'm getting a NullPointerException
, because the path
is a directory.
编辑:CustomFileFilter
类如下:
public class CustomFileFilter implements FileFilter {
// Determine if the file should be accepted
@Override
public boolean accept(File file) {
// If the file isn't a directory
if(file.isDirectory()) {
// Accept it
return true;
} else if(file.getName().endsWith("txt")) {
// Accept it
return true;
}
// Don't accept it
return false;
}
}
推荐答案
将此添加到AndroidManifest.xml:
Add this to AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
此权限允许您读取文件;如果您不使用此权限,则listFiles()
和list()
都将抛出NullPointerException
.
This permission allow you to read files; if you don't use this permission then listFiles()
and list()
will both throw NullPointerException
.
这是显示/storage/emulated/0/Download
中所有文件的示例:
And here is an example of showing all files in /storage/emulated/0/Download
:
String dir = "/storage/emulated/0/Download/";
File f = new File(dir);
String[] files = f.list();
for(int i=0; i<files.length; i++){
Log.d("tag", files[i]);
}
这篇关于为什么在目录上调用File.listFiles时可以返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!