我正在创建一个 Android 应用程序,我想列出目录中的文件。我通过调用来做到这一点
File[] files = path.listFiles(new CustomFileFilter());
path
is a File
对象,通过调用创建
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
当我尝试获取长度时files
通过调用数组
int length = files.length;
这条线给了我一个NullPointerException
, 因为files
一片空白。
我已经检查过是否path
我尝试通过调用列出存在的文件
System.out.println("Path exists: " + path.exists());
当我运行该应用程序时,它会打印
Path exists: true
在 Android Studio 控制台中,因此该目录存在。
我还打印了路径名,即
/storage/emulated/0/Download
So the path
是一个目录,而不是一个文件。
我不知道为什么我会得到一个NullPointerException
,因为path
是一个目录。
EDIT: The 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;
}
}