简体   繁体   中英

How do I read and write a file on Phonegap?

I was looking through the FileWriter and FileReader APIs for Cordova and I understand that they are asynchronous.

I've also managed to get FileWriter and FileReader to work separately by just following the full examples here.

But I was wondering if there was a way to read a file immediately after writing to it. The code below shows what I want to do in 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 in the full example from the documentation requires a file object to read something (that the gotFileWriter method lacks a reference to). However, most of the asynchronous process for reading files is similar to writing files.

If I wanted to read the file after writing it, would I have to start the entire asynchronous process again with a call to window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); in the onwriteend function? Along with a different gotFileEntry method that calls fileEntry.file() ? Or is there a way to just get the file object from within the gotFileWriter method without having to repeat these steps?

Does anyone know the fastest way of doing it?

Create, Read, Edit and Delete example

Before I show the examples I want to say that I use the externalDataDirectory (file:///data/user/0/com.adobe.phonegap.app/files/) in the examples, because this directory is public so you can check the file for existence and changes on your phone. The generated file should be in your internal storage.

The examples are meant to follow up on each other.

Generating a file > reading the generated file > editing the generated file > deleting the generated file.

An example of how to write a file:

 //
 //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);  });

An example of how to read a 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);
        };
        reader.readAsText(file);
    }, function(e) { console.log('opening file error'); console.log(e); });
}, function error(e) { console.log('resolving directory error'); console.log(e);  });

An example of how to edit a file:

The javascript function replace is being used in the example. I haven't found another way to edit a file yet.

 //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);  });

An example of how to delete a file:

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); 
    });
});

Use this Function on Starting of Your Application. It Will read and write the files. Try it.

 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);
               }
           }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM