您的位置:首页 > 其它

PhoneGap读写SD卡——文本文件方式

2014-11-13 11:24 218 查看
1、从SD卡中的文本文件读取数据

<script type="text/javascript" charset="utf-8">
//等待加载PhoneGap
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap加载完毕
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
//获取newFile目录,如果不存在则创建该目录
function gotFS(fileSystem) {
newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false}, readerFile, fail);
}
//获取newFile目录下面的dataFile.txt文件,如果不存在则创建此文件
function readerFile(newFile) {
newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);
}

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

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

function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
var resultString = evt.target.result;

while(resultString.length > 0) {
var cellString = resultString.substring(0,resultString.indexOf("::::"));
var resultString = resultString.substring(resultString.indexOf("::::") + 4, resultString.length);
var ad=document.getElementById('myBody');
var adiv=document.createElement('div');
adiv.textContent = cellString;
adiv.id="kkk";
ad.appendChild(adiv);

var hr = document.createElement('hr');
ad.appendChild(hr);
}
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}
</script>


2、向SD卡中写数据,以文本文件格式存储

<script type="text/javascript" charset="utf-8">
//等待加载PhoneGap
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap加载完毕
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
//获取newFile目录,如果不存在则创建该目录
function gotFS(fileSystem) {
newFile = fileSystem.root.getDirectory("newFile", {create : true,exclusive : false}, writerFile, fail);
}
//获取newFile目录下面的dataFile.txt文件,如果不存在则创建此文件
function writerFile(newFile) {
newFile.getFile("dataFile.txt", {create : true,exclusive : false}, gotFileEntry, fail);
}

function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}

function gotFileWriter(writer) {
//onwrite:当写入成功完成后调用的回调函数
writer.onwrite = function(evt) {
navigator.notification.alert("添加成功!", null, "提示", "知道了");
};
writer.seek(writer.length);	//相当于文件光标
writer.write("the text you want to write into the file"); //参数为要写入文件的内容
}

function fail(error) {
alert("Failed to retrieve file:" + error.code);
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: