在Javascript(PhoneGap)中使用循环将10行写入文件失败

时间:2013-04-24 13:06:13

标签: java javascript android cordova for-loop

我正在尝试使用循环将至少10行写入文件,以使用PhoneGap在文件中追加多行,但每次我在下面运行此代码时,只能将1行添加到文件作为换行符。但是在10次迭代中没有打印10行。请建议我如何使用phoneGap javascript纠正我的问题。

function gotFileWriter(writer) {

                    for (var z = 0; z<= 10; z++) {

                        console.log("normal write success");

                        writer.onwrite = function(evt) {

                            console.log("write success");
                        };


                        writer.onwriteend = function(evt) {

                            console.log("write end");
                        }

                        writer.seek(writer.length);
                        writer.write("id,updated,created,fname,lname,company,tags,type,label,value,source,sourceid\r\n");
                        writer.abort();    // I tried even commenting
                    }
}

3 个答案:

答案 0 :(得分:0)

你试试这个吗?

function gotFileWriter(writer) {

    console.log("normal write success");

    writer.onwrite = function(evt) {
        console.log("write success");
    };


    writer.onwriteend = function(evt) {
        console.log("write end");
    }


    for (var z = 0; z< 10; z++) {

        writer.seek(writer.length);
        writer.write("id,updated,created,fname,lname,company,tags,type,label,value,source,sourceid\r\n");
        writer.abort();    // I tried even commenting
    }
}

答案 1 :(得分:0)

这对我来说很有把戏

构建一个大字符串:

function gotFileWriter(writer)
{
  var bigString = '';
  for (var i=0; i<numberOfLines; i++)
  {
    bigString += line[i];
    bigString += '\r\n';
  }
...

然后对文件进行大量写入:

...
  writer.onwrite = function (evt) { ... };
  writer.onwriteend = function (evt) { ... };
  writer.seek(writer.length);
  writer.write (bigString);
}

答案 2 :(得分:0)

您可以使用它将文本附加到文件而不是循环

function gotFileWriter(writer) {
    writer.seek(writer.length);
    writer.write(" - append- \n");
}