关于在安卓程序中本地文件操作。
这几天再弄一个phonegap项目,比较老了,一两年前的版本,具体忘了那个版本。在网上找了一个例子,发现本地写入文件,删除文件,查看本地目录都可以使用,但是read功能总是没法实现,总是显示null,error.code显示json error。百度了一下午,各种调试都没弄好,非常费解,到底哪里出问题了。只好来论坛求助,希望各位大大帮帮我。代码:function readFile(f) {
reader = new FileReader();
reader.onloadend = function(e) {
console.log("go to end");
logit("<pre>" + e.target.error.code + "</pre><p/>");
logit("<pre>" + e.target.result + "</pre><p/>");
}
reader.readAsText(f);
}
function doReadFile(e) {
fileSystem.root.getFile("test.txt", {create:true}, readFile, onError);
}
function appendFile(f) {
f.createWriter(function(writerOb) {
writerOb.onwrite=function() {
logit("Done writing to file.<p/>");
}
//go to the end of the file...
writerOb.seek(writerOb.length);
writerOb.write("Test at "+new Date().toString() + "\n");
})
}
function doAppendFile(e) {
fileSystem.root.getFile("test.txt", {create:true}, appendFile, onError);
}
function gotFiles(entries) {
var s = "";
for(var i=0,len=entries.length; i<len; i++) {
//entry objects include: isFile, isDirectory, name, fullPath
s+= entries.fullPath;
if (entries.isFile) {
s += " ";
}
else {
s += " ";
}
s += "<br/>";
}
s+="<p/>";
logit(s);
}
function doDirectoryListing(e) {
//get a directory reader from our FS
var dirReader = fileSystem.root.createReader();
dirReader.readEntries(gotFiles,onError);
}
function onFSSuccess(fs) {
fileSystem = fs;
//getById("#dirListingButton").addEventListener("touchstart",doDirectoryListing);
//getById("#addFileButton").addEventListener("touchstart",doAppendFile);
getById("#readFileButton").addEventListener("touchstart",doReadFile);
//getById("#metadataFileButton").addEventListener("touchstart",doMetadataFile);
//getById("#deleteFileButton").addEventListener("touchstart",doDeleteFile);
logit( "Got the file system: "+fileSystem.name +"<br/>" +
"root entry name is "+fileSystem.root.name + "<p/>")
doDirectoryListing();
}
function onDeviceReady() {
//request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onError);
}
function init() {
document.addEventListener("deviceready", onDeviceReady, true);
}
</script>
<style>
button { width: 100%; padding: 5px; }
</style>
</head>
<body id="stage" class="theme">
<!-- <button id="addFileButton">Create/Append to Test File</button> -->
<button id="readFileButton">Read Test File</button>
<!--<button id="metadataFileButton">Get Test File Metadata</button>-->
<!--<button id="deleteFileButton">Delete Test File</button>-->
<!--<button id="dirListingButton">Show Directory Contents</button>-->
<div id="content"></div>
</body>
</html>
篇幅限制,贴了部分代码 wgwntp 发表于 2015-7-23 19:34
篇幅限制,贴了部分代码
看看官方文档用最新的cordova试试,老版本可能不是很稳定
也可以下载个ng-cordova 看看里面代码怎么写的
其实官方文档已经有代码的
页:
[1]