我是否正在使用Android使用文件概念创建示例应用程序
以下步骤为:
--- 1.我给出父文件夹名称"默认"
--- 2.找到子文件夹的父文件夹。
--- 3.列出子文件夹文件。
--- 4.删除清空子文件夹
我将完成三个步骤,在问题是如何查找子文件夹为空给我一个解决方案?
示例代码:
File filefirst = new File("/storage/sdcard0/Parentfoldername/");
String[] names = filefirst.list();
for (String name : names)
{
if (new File("/storage/sdcard0/Parentfoldername/" + name).isDirectory()) {
File directory = new File("/storage/sdcard0/Parentfoldername/" + name);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile())
{
if (directory.isDirectory())
{
String[] children = directory.list();
for (int i = 0; i < children.length; i++)
{
new File(directory, children[i]).delete();
}
}
}
}
}
}
这段代码就像删除文件里面的sub_folder一样,删除了sub_folder而不是文件夹是文件,但是没有删除空的sub_folder。
答案 0 :(得分:0)
public class Utils {
/**
* Empty and delete a folder (and subfolders).
* @param folder
* folder to empty
*/
public static void rmdir(final File folder) {
// check if folder file is a real folder
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null) {
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) {
rmdir(tmpF);
}
tmpF.delete();
}
}
if (!folder.delete()) {
System.out.println("can't delete folder : " + folder);
}
}
}
}