PhoneGap(Android)删除目录

时间:2012-11-13 04:34:43

标签: android cordova

我正在尝试使用以下内容PhoneGap on Android删除目录及其内容:

deleteDirectory = function deleteDirectory(uri) {
    uri = uri.substring(0, uri.lastIndexOf('/'));
    return $.Deferred(function (def) {
        fileSystem.root.getDirectory(uri, {
            create: false
        }, function (directory) {
            directory.removeRecursively();
            def.resolve();
        }, function (error) {
            resolveError("Error deleting directory: ", error, def);
        });
    }).promise();
}

出现以下错误:File No Modification Allowed Error

我已确认此权限已设置:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我还应该在哪儿看?

2 个答案:

答案 0 :(得分:10)

我用这种方法做到了:



    function ClearDirectory() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
        function fail(evt) {
            alert("FILE SYSTEM FAILURE" + evt.target.error.code);
        }
        function onFileSystemSuccess(fileSystem) {
            fileSystem.root.getDirectory(
                 "yours/dir/ect/ory",
                {create : true, exclusive : false},
                function(entry) {
                entry.removeRecursively(function() {
                    console.log("Remove Recursively Succeeded");
                }, fail);
            }, fail);
        }
    }


答案 1 :(得分:1)

来自此answer

  

如果要访问,建议使用 resolveLocalFileSystemURL   cordova.file。*(例如cordova.file.dataDirectory)下的位置,其中   在大多数情况下(如果不是总是这样),如果您使用 requestFileSystem   需要有权访问文件系统的根。

这还节省了一些代码行,并且更具可读性:

deleteFolder(fileName: string) {
    const uri = `${cordova.file.dataDirectory}${fileName}`;
    window.resolveLocalFileSystemURL(uri, (dirEntry: DirectoryEntry) => {
        dirEntry.removeRecursively(
            () => console.log('successfully deleted the folder and its content'),
            e => console.error('there was an error deleting the directory', e.toString())
        )
    });
}

这是一个值得期待的版本:

deleteFolder(fileName: string): Promise<void> {
    const promise = new Promise<void>((resolve, reject) => {
        const uri = `${cordova.file.dataDirectory}${fileName}`;
        window.resolveLocalFileSystemURL(uri, (dirEntry: DirectoryEntry) => {
            dirEntry.removeRecursively(() => resolve(), e => reject(e));
        }, e => reject(e));
    });
    return promise;
}