[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就好了
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);
};
標籤:
Cordova
,
Javascript
,
Visual Studio
-- Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer. 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力...