`

cordova读写文件(2)

阅读更多
上一篇讲的是如何将数据写入文件
这篇讲如何读取文件。

var storeNotification="on";//data read
var filePath = "mobovip/stores.txt";//default file path

function read(filePath) {
	this.filePath = filePath;
	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
};

function gotFS(fileSystem) {
	fileSystem.root.getFile(filePath, {
		create : true,
		exclusive : false
	}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
	fileEntry.file(gotFile, fail);
}

function gotFile(file) {
	//readDataUrl(file); 
	readAsText(file);
}

function readAsText(file) {
	var reader = new FileReader();
	reader.onloadend = function(evt) {
		//console.log("Read as text"); 
//		console.log("result=" + evt.target.result);
		storeNotification=evt.target.result;//将读取到的数据赋值给变量
		if(storeNotification==null||storeNotification.length==0){
			storeNotification="on";
		}
	};
	reader.readAsText(file);

}

function readDataUrl(file) {
	var reader = new FileReader();
	reader.onloadend = function(evt) {
		console.log("Read as data URL");
		console.log(evt.target.result);
	};
	reader.readAsDataURL(file);
}

function fail(evt) {
	console.log("code=======" + evt.target.error.code);
}



使用很简单:

read("mobovip/notification.txt");
其中参数是需要读取文件的路径。

在readAsText(file)方法中有一个回调reader.onloadend,当读取成功后,evt.target.result就是取到的数据。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics