Phonegap Android:读取文件并保存到localstorage

时间:2014-04-01 06:24:30

标签: javascript android html5 cordova

上午。

我使用以下代码(Phonegap 2.9)在Android设备上创建/读取文件。

function gotFS(fileSystem) {
            //alert('first try');
            savedFS = fileSystem;
            fileSystem.root.getFile("dp-locations.json", null, gotFileEntry2, fail);
        }

        function gotFS2(fileSystem) {
            //alert('try again');
            fileSystem.root.getFile("dp-locations.json", {create: true}, gotFileEntry, fail);
        }

        function gotFileEntry(fileEntry) {
            //alert('call writer');
            fileEntry.createWriter(gotFileWriter, fail);
        }

         function gotFileEntry2(fileEntry) {
            alert('fileentry2');
            //fileEntry.createWriter(gotFileWriter, fail);
            fileEntry.file(gotFile, failRead);
        }

        function gotFile(file){
        alert('gotfile');
            readAsText(file);
        }

        function readAsText(file) {
            alert('here I am');
            var reader = new FileReader();
            reader.onloadend = function(evt) {
                alert("Read as text");
                alert("rat2: "+evt.target.result);
            };

            reader.readAsText(file);
            reader.onload = function(evt){
                alert(reader.result);
            };
            }

        function failRead(evt) {
            alert("112: "+evt.target.error.code);
        }

        function gotFileWriter(writer) {
            writer.onwrite = function(evt) {
                //console.log("write success");
            };
            //writer.write('{"routes": {}}');//start writing to JSON file
            var routes = new Array();
            var test = new Object({"locations":[{"name":"first","values":["cw11 1gb","po45 5wd","ta6 3eq"]},{"name":"second","values":["cw7 2yg","po4 8ej","ta9 3zd"]}]});
            routes.push(test);
            writer.write(routes);//start writing to JSON file
            gotFileEntry2(fileEntry);            
        }

        function fail(error) {
            //console.log(error.code);
            if(error.code == 1){
                alert('not found');
                gotFS2(savedFS);
            }
            alert(error.code);
        }

我的问题是脚本正在创建文件(如果需要),但是,当文件存在时,它似乎不会读取它。

调用函数gotFile,但函数readAsText似乎没有按要求执行。 我希望将文件内容添加到localStorage。

我错过了什么?

0 个答案:

没有答案