检查一个文件夹是否为空(内部存储)
问题描述:
我有后续的麻烦。我的应用程序应读取文件列表并向用户显示其名称。 当应用程序第一次启动时,我需要为应用程序创建一个特定的文件夹? 那么我该如何检查它是否为空?检查一个文件夹是否为空(内部存储)
答
假设您创建在内部存储的目录,你可以得到子对象的数量在目录这样
File dir = context.getDir("somePath", Context.MODE_PRIVATE);
File[] children = dir.listFiles();
if(children.length > 0)
{
// the directory is not empty
}
else
{
// the directory is empty.
}
这仅仅是一个快速的示例代码。更好的方法是使用自定义FileFilter
和dir.listFiles()
排除自我和父代别名,因为我不确定它们将始终从结果列表中排除。
答
下面的代码将检查是否有文件夹已经存在,如果不创建一个,并警告你,如果错误创建一个:如果路径存在与否和path.exists()
简单地为您创建一个
// check if appfolder is created and if not through an
// exception
File path = new File("yourDir");
if (!path.exists()) {
if (!path.mkdirs()) {
try {
throw new IOException(
"Application folder can not be created. Please check if your memory is writable and healthy and then try again.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
} else {
Log.i("app", "directory is: " + path.getPath());
}
exists()
检查。