我正在使用Cordova / ionic编写应用,现在我正尝试使用$cordovaFile plugin将文件写入文件系统。所以我尝试了文档中的代码(添加了一些日志记录):
$cordovaFile.writeFile(cordova.file.dataDirectory, "file.txt", "the text inside the file", true)
.then(function (success) {
console.log('SUCCESS: ' + JSON.stringify(success));
}, function (error) {
console.log('ERROR: ' + JSON.stringify(error));
});
但这会返回ERROR: {"code":5}
5
引用ENCODING_ERR
。
所以在尝试了一些不同的组合之后,将第一行改为此(所以没有dir):
$cordovaFile.writeFile("file14.txt", "text", true)
返回(为便于阅读而格式化):
SUCCESS: {
"type": "writeend",
"bubbles": false,
"cancelBubble": false,
"cancelable": false,
"lengthComputable": false,
"loaded": 0,
"total": 0,
"target": "fileName": "",
"length": 4,
"localURL": "cdvfile://localhost/persistent/file14.txt",
"position": 4,
"readyState": 2,
"result": null,
"error": null,
"onwritestart": null,
"onprogress": null,
"onwrite": null,
"onabort": null,
"onerror": null
}
所以我尝试使用以下方法读出同一个文件:
$cordovaFile.readAsText("file14.txt")
.then(function (success) {
console.log('SUCCESS: ' + JSON.stringify(success));
}, function (error) {
console.log('ERROR: ' + JSON.stringify(error));
});
令我惊讶的是,它只返回一个空字符串:SUCCESS: ""
所以我现在想知道:
5 ENCODING_ERR
?答案 0 :(得分:0)
这个 tutorial 很容易理解,它适用于intel xdk但是它使用了cordova,所以只要你有cordova就可以工作(它与intel xdk无关) api),只需确保代码中定义了cordova.file
对象。
请注意,从版本1.2开始,cordova文件系统发生了巨大变化,请注意当前版本1.3.3在从当前工作区(www文件夹)加载文件时有一些错误,但是写入和读取文件到从应用程序存储文件夹或内部存储没有任何问题。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);
}
function onSuccess(fileSystem)
{
var directoryEntry = fileSystem.root;
//lets create a file named readme.txt. getFile method actually creates a file and returns a pointer(FileEntry) if it doesn't exist otherwise just returns a pointer to it. It returns the file pointer as callback parameter.
directoryEntry.getFile("readme.txt", {create: true, exclusive: false}, function(fileEntry){
//lets write something into the file
fileEntry.createWriter(function(writer){
writer.write("This is the text inside readme file");
}, function(error){
console.log("Error occurred while writing to file. Error code is: " + error.code);
});
}, function(error){
console.log("Error occurred while getting a pointer to file. Error code is: " + error.code);
});
}
function onError(evt)
{
console.log("Error occurred during request to file system pointer. Error code is: " + evt.code);
}