我想在JAVA中删除文件夹(目录)和子目录,我的文件和文件夹为空时需要2个条件。我已经被搜查并尝试了我找到的所有例子,但没有奏效。即使该代码有效,也只是删除文件或只删除1个文件夹(目录级别4)而不是所有文件夹。
我想删除旧目录year \ place \ owner \ month \ file。
File source = new File("C:\\Users\\Workspaces\\projects\\uploadFolder\\year\\place\\owner\\month\\file");
Path sources = source.toPath();
我试过这个:
public static void rmdir(final File 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);}}
}
此:
public static void deleteDirectory(File path)
{
if (path == null)
return;
if (path.exists())
{
for(File f : path.listFiles())
{
if(f.isDirectory())
{
deleteDirectory(f);
f.delete();
}
else
{
f.delete();
}
}
path.delete();
}
}
这:
public static void deleteFiles (File file)
{
if(file.isDirectory())
{
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
file.delete();
}
}
此:
FileUtils.deleteDirectory(source);
此:
Files.delete(sources);