我正在使用cordova在Visual Studio 2012上开发Windows应用程序。我尝试创建,然后读取.txt文件的内容。
这就是我试过的,
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
// alert("File created");
fileSystem.root.getFile("textfile.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
// alert(fileEntry.fullPath);
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
/*writer.onwrite = function(evt) {
fileRead();
alert("write success");
console.log("write success");
}; */
/* writer.onerror = function(evt) {
alert("Writing abort");
}; */
/* writer.onprogress = function(evt) {
alert("Progress writing file");
}; */
writer.onwritestart = function(parents) {
// alert("Starts" + parents);
}
writer.onwriteend = function(parent) {
alert("Success or Fail "+ parent.target);
};
writer.write("some sample text");
// alert("Writing Data" + writer);
// contents of file now 'some sample text'
writer.truncate(11);
// contents of file now 'some sample'
writer.seek(4);
// contents of file still 'some sample' but file pointer is after the 'e' in 'some'
writer.write(" different text");
// contents of file now 'some different text'
}
function fileRead(){
//alert("inside file read");
fileSystem.root.getFile('textfile.txt', {create: false, exclusive: false}, gotFileEntryForRead, fail);
}
function gotFileEntryForRead(fileEntry) {
alert(fileEntry);
//alert("inside got file entry for read");
fileEntry.file(gotFile, fail);
}
function gotFile(file){
//readDataUrl(file);
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 readAsText(file) {
//alert("inside readAsText");
var reader = new FileReader();
reader.onloadend = function(evt) {
if(evt.target.result == null) {
alert("File doesn't exists");
} else {
alert("File exists");
}
alert(evt.target.result);
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
alert("Fail");
//alert("Error:" + evt.target.error.code);
//console.log(evt.target.error.code);
}
文件是在调用属性onwrite
时创建的,但当我尝试使用alert alert(evt.target.result);
查看文件内容时,没有任何内容发生。
请帮忙
由于
答案 0 :(得分:2)
您正在使用gotFileEntry,onDeviceReady和gotFS函数中的失败函数。这些函数执行requestFileSystem,getFile和writeFile功能。你会如何调试哪里出错?因此,编写单独的失败处理函数以轻松转错,然后修复错误。在这种情况下,您将无法准确地收到错误。
其次检查您是否已在cordova文件中添加权限。
提示:某些时间模拟器不像真实设备那样提供完整功能。还可以在真实设备中测试应用程序。