写入和读取文件中的PhoneGap文件、PhoneGap

2023-09-04 05:35:36 作者:清莲茉茉

我试过读/写文件中的 PhoneGap的+安卓,这里是设置了:

I tried writing/reading a file in phonegap+android, here is the set up:

$(document).ready(function() {
    document.addEventListener("deviceready", deviceready, true);

    $(document).bind("deviceready", function(){
    //writeFile();
    //readFile();
    });
});

function deviceready() {
    writeFile();
    readFile();
}

// This is just to do this.
function readFile() {
    var d = navigator.file.read('/sdcard/foo.xml', success(), fail());
    console.warn(d);
}

function writeFile() {
    navigator.file.write('/sdcard/foo.xml', "This is a test of writing to a file",
            success(), fail());
}

但在模拟器的Andr​​oid 2.2 ,我得到了以下错误消息:

But on the emulator for Android 2.2, I got the following error message:

08-06 14:21:29.428: INFO/Web Console(936): Error in success callback: Network Status1 = TypeError: Result of expression 'navigator.file' [undefined] is not an object. at file:///android_asset/www/phonegap.0.9.6.js:649

还有什么人失踪,有什么可以尝试?

What could be missing and what could be tried?

推荐答案

对我来说,下面的工作在Android与PhoneGap的-1.0.0:

The following works for me on Android with phonegap-1.0.0:

<script type="text/javascript" charset="utf-8" src="css-js/phonegap-1.0.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for PhoneGap to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    //
    function onDeviceReady() {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);

    }

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

    }

    function gotFileEntry(fileEntry) {

        fileEntry.createWriter(gotFileWriter, fail);
    }

    function gotFileWriter(writer) {
        writer.onwrite = function(evt) {
            console.log("write success");
        };
        writer.write("some sample text");
</script>