我正在创建一款Android应用,想要列出一个文件夹中的文件。我通过调用以下方法来实现:
File[] files = path.listFiles(new CustomFileFilter());
path
是一个 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
所以path
是一个目录,而不是文件。
我不知道为什么会出现NullPointerException
,因为path
是一个目录。
编辑: 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;
}
}
CustomFileFilter
类的原因,您在数组中没有获取到任何文件。请尝试使用path.listFiles()
方法来运行相同的代码。 - ρяσѕρєя Kpath.isDirectory()
和path.canRead()
的输出。仅仅因为你说它是一个文件并不意味着它就是一个文件。 - chrylis -cautiouslyoptimistic-