如何在Phonegap上读写文件?

时间:2013-08-24 06:09:48

标签: javascript file cordova

我正在查看Cordova的FileWriter和FileReader API,我知道它们是异步的。

我还设法通过跟随full examples here.

让FileWriter和FileReader分开工作

但是我想知道在写入文件后是否有办法立即读取文件。下面的代码显示了我想在gotFileWriter

中执行的操作
function onDeviceReady() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
    fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
    fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
    writer.onwriteend = function(evt) {
        // Read the file after writing
    };
    writer.write("some sample text");
}

function fail(error) {
    console.log(error.code);
}

文档中的完整示例中的FileReader需要file个对象来读取某些内容(gotFileWriter方法缺少引用)。但是,大多数用于读取文件的异步过程与写入文件类似。

如果我想在编写文件后读取文件,是否必须通过调用window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);函数中的onwriteend再次启动整个异步过程?以及调用gotFileEntry的其他fileEntry.file()方法?或者有没有办法从file方法中获取gotFileWriter对象而不必重复这些步骤?

有没有人知道最快的做法?

2 个答案:

答案 0 :(得分:0)

创建,读取,编辑和删除示例

在显示示例之前,我想说的是在示例中使用externalDataDirectory(file:///data/user/0/com.adobe.phonegap.app/files/),因为目录是公共目录,因此您可以在手机上检查文件是否存在和更改。生成的文件应该在您的内部存储器中。

这些示例旨在相互补充。

生成文件> 读取生成的文件> ,编辑生成的文件> ,删除生成的文件。

如何编写文件的示例:

 //
 //resolve url for directory entry for putting in new file
 //cordova.file.externalDataDirectory / file:///data/user/0/com.adobe.phonegap.app/files/
 //
 window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function success(dataDirEntry) {
     //create new file         
     dataDirEntry.getFile("test.txt", { create: true, exclusive: false }, function (newFileEntry) {

         // Create a FileWriter object for our newFileEntry             
         newFileEntry.createWriter(function (fileWriter) {

             fileWriter.onwriteend = function () {
                 console.log("Successful file write...");                                   
             };

             fileWriter.onerror = function (e) {
                 console.log("Failed file write: " + JSON.stringify(e));
             };

             //type can be 'text/plain' or newFileEntry.type for .txt             
             var blob = new Blob(['test it works'], { type: newFileEntry.type });
             //console.log(blob);                               

             fileWriter.write(blob);                               
         });
    }, function(e) { console.log('creating file error'); console.log(e); });
}, function error(e) { console.log('resolving directory error'); console.log(e);  });

如何读取文件的示例:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory+'test.txt', function success(fileEntry) {
    //read file
    fileEntry.file(function (file) {
        var reader = new FileReader();
        reader.onloadend = function() {
            var fileData = this.result;
            console.log(fileData);
        };
        reader.readAsText(file);
    }, function(e) { console.log('opening file error'); console.log(e); });
}, function error(e) { console.log('resolving directory error'); console.log(e);  });

如何编辑文件的示例:

该示例中使用了JavaScript函数replace。我还没有找到另一种编辑文件的方法。

 //resolve url for file entry for reading the file    
 //
 window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory+'test.txt', function success(fileEntry) {
     //read file
     fileEntry.file(function (file) {
         var reader = new FileReader();
         reader.onloadend = function() {
             var fileData = this.result;
             console.log(fileData);
             //replace test with yes
             fileData = fileData.replace('test', 'yes');

             // write the edited filedata to the file
             // Create a FileWriter object for our fileEntry
             fileEntry.createWriter(function (fileWriter) {

                 fileWriter.onwriteend = function () {
                     console.log("Successful file write...");
                 };

                 fileWriter.onerror = function (e) {
                     console.log("Failed file write: " + JSON.stringify(e));
                 };

                 //type can be 'text/plain' or newFileEntry.type for .txt
                 var blob = new Blob([fileData], { type: fileEntry.type });
                 //console.log(blob);

                 fileWriter.write(blob);
             });
         };
         reader.readAsText(file);
     }, function(e) { console.log('opening file error'); console.log(e); });
}, function error(e) { console.log('resolving directory error'); console.log(e);  });

如何删除文件的示例:

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory+'test.txt', function success(fileEntry) {
    fileEntry.remove(function() {
        console.log('file deleted');
    }, function(e) {
        console.log('file not deleted');
        console.log(e); 
    });
});

答案 1 :(得分:-3)

在启动应用程序时使用此功能。 它将读取和写入文件。试试吧。

 function onDeviceReady() {
               window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
               window.resolveLocalFileSystemURI("file:///example.txt", onResolveSuccess, fail);
               var isApp = 'yes';
               var root = this;
               cb = window.plugins.childBrowser;
               call();
           }

           function onFileSystemSuccess(fileSystem) {
               console.log(fileSystem.name);
           }

           function onResolveSuccess(fileEntry) {
               console.log(fileEntry.name);
           }

           function fail(evt) {
               console.log(evt.target.error.code);
           }


           function call(){
               window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, successDirectoryReader, null);

           }
function successDirectoryReader(fileSystem)
           {
               try {
                   var dirEntry = fileSystem.root;
                   var directoryReader = dirEntry.createReader();
                   directoryReader.readEntries(success,failure);
               } catch (e) {
                   alert(e);
               }
           }