Android删除文件夹(文件夹以及文件夹下所有的文件)

Cocos2dx FileUtils::getInstance()->removeDirectorys删除文件夹,在Android上有些问题,。查看源码之后发现实现是下面这样:

bool FileUtils::removeDirectory(const std::string& path)
{
    // FIXME: Why using subclassing? an interface probably will be better
    // to support different OS
    // FileUtils::removeDirectory is subclassed on iOS/tvOS
    // and system() is not available on tvOS
#if !defined(CC_PLATFORM_IOS)
    if (path.size() > 0 && path[path.size() - 1] != '/')
    {
        CCLOGERROR("Fail to remove directory, path must terminate with '/': %s", path.c_str());
        return false;
    }

    std::string command = "rm -r ";
    // Path may include space.
    command += """ + path + """;
    if (system(command.c_str()) >= 0)
        return true;
    else
#endif
        return false;
}

通过代码看出,是用过 rm 移除。。。。

解决方案

1种使用lua方式实现 。参考  http://zengrong.net/post/2129.htm

第二种是使用Android的删除。我这里使用的第二种

源码奉上:

import java.io.File; 


    //删除文件夹和文件夹里面的文件
    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

c++调用java ,lua调用c++这里就不说啦。

原文地址:https://www.cnblogs.com/zhangfeitao/p/6733872.html