PhoneGap: save a text file in the internal storage

2019-04-18 03:15发布

问题:

this may seem a repeated question but none of the answers or tutorials I found could help me :( . I'm beginner with the phongap. I would like to save a text file in a specific folder in the internal storage of the android device (android 4.4).

I have used the exact code mentioned in the phonegap documents (the "Full Example" one) and I have given the needed permissions in the manifest. (http://docs.phonegap.com/en/2.6.0/cordova_file_file.md.html#FileWriter) after compiling it by the phonegap and running it on the device, When I connect the android device to the PC, I can not find the file anywhere. I guess the file is not accessible by the PC.

The question is how should I change the code to make it accessible by PC (when it is connected through USB cable)? so I can copy and paste the text file to the PC.

or is there any sample phonegap project out there that cover this ? so I can try to analyze each line of the codes.

Many thanks in advance for any help..

回答1:

I suggest you read the section Where to store files in the cordova file plugin documentation.

It will show you the different folders you can use depending on the platform and if the file is public or not.

Here is a code sample on how to write a file yourfile.txt to the folder /Android/data/yourapppackageid/files. You have to replace yourapppackageid with the id of your app which should be accessible from your computer.

window.resolveLocalFileSystemURL(cordova.file.dataDirectory,
    function(dirEntry) {
        dir.getFile("yourfile.txt", {
            create: true,
            exclusive: false
        }, function(f) {
        f.createWriter(function(writer) {
            writer.onwriteend = function(evt) {
                alert("File successfully created!");
            };
            writer.write("Hello world!");
        },
        function(evt, where) {
            console.log("Error writing file "+ where + " :");
            console.log(JSON.stringify(evt));
        }
    },
    function(evt, where) {
        console.log("Error resolving data folder "+ where + " :");
        console.log(JSON.stringify(evt));
    }
);