[Cordova] 簡單筆記一下寫入檔案和讀取檔案

2015-10-02

今天筆記一下,關於Cordova 寫入檔案的方法,主要參考連結為
https://cordova.apache.org/docs/en/3.0.0/cordova_file_file.md.html
http://www.raymondcamden.com/2014/11/05/Cordova-Example-Writing-to-a-file

1.首先要加入plugin ,文中我加入兩個 File , Notification 因為 Notification 我很常用到,事實上只需要File就好了
image

2. 寫入 的 function



function WriteData(filename, str) {
     /// <summary>
     /// 寫入檔案
     /// </summary>
     /// <param name="filename">檔名</param>
     /// <param name="str">內容</param>
     window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dir) {
         dir.getFile(filename, { create: true }, function (file) {
 
             file.createWriter(function (fileWriter) {
                 fileWriter.write(str);
             }, function (ex) {
                 navigator.notification.alert(ex.target.error.code, null, 'Error', 'OK');
 
             });
         });
     });
 
 }

3.讀取的function


function ReadFileString(filename, succFunc) {
     /// <summary>
     /// 讀取資料
     /// </summary>
     /// <param name="filename">檔名</param>
     /// <param name="succFunc">成功的呼叫事件</param>
     window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dir) {
         dir.getFile(filename, { create: true }, function (fileObject) {
             fileObject.file(function (file) {
                 var reader = new FileReader();
                 reader.onloadend = function (e) {
                     succFunc(this.result);
                 };
                 reader.readAsText(file);
             }, function (ex) {
                 navigator.notification.alert(ex.target.error.code, null, 'Error', 'OK');
                
             });
         });
     });
 
 }

4. 呼叫


function message1(str) {
    navigator.notification.alert(str, null, 'Info', 'OK');
}
 
$('#btnWrite').attr('onclick', 'btnWrite_click()');
 
function btnWrite_click() {
    WriteData("xxx.txt", "許當麻" + new Date());
 
    ReadFileString("xxx.txt", message1);
 
};

結果:
Screenshot_2015-10-02-17-46-46
範例:


當麻許的超技八 2014 | Donma Hsu Design.