无法写入钛中的文件

Cannot write to file in Titanium

本文关键字:文件      更新时间:2023-09-26

我在写入 Titanium Studio 中的文件时遇到问题。特别是.json文件。代码已编译完成,未引发异常。

这是我的相关代码部分,在添加元素之前,我先将文件解析为 var,然后将其字符串化以写回。阅读效果很好,添加元素也是如此,写作过程有问题

var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
    var jsontext = file.read().toString();
    var jsondoc = JSON.parse(jsontext);
    jsondoc['feedlist'].push({
        "picloc":imagename,
        "title":titlef.value,
        "desc1":descf1.value,
        "desc2":descf2.value,
        "desc3":descf3.value
        });
    jsontext = JSON.stringify(jsondoc);
    file.write(jsontext); // write(data,[append])

注意:我已经查阅了文档并做了一些自己的搜索,有些人建议应该使用"Filestream"代替普通文件以及.close(),我还没有让它们工作,但如果有人知道如何让它工作,这可能是解决方案的指针

提前谢谢。

编辑:这个问题被标记为重复,最初我认为这是两个单独的问题,一个是关于将文本写入文件。另一种方法是将event.media(图片)解析为文件。

我现在让它工作了,问题是我试图写入只读目录中的文件

Ti.Filesystem.resourcesDirectory:应用程序资源所在的只读目录

Ti.Filesystem.applicationDataDirectory:应用可访问的读/写目录。此目录的内容保留直到您删除文件或直到用户卸载应用程序

这是我的代码,目录被修改了

var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = sesfile.read().toString();
var jsondoc = JSON.parse(jsontext);
jsondoc['feedlist'].push({
    "picloc":imagename,
    "title":titlef.value,
    "desc1":descf1.value,
    "desc2":descf2.value,
    "desc3":descf3.value
    });
jsontext = JSON.stringify(jsondoc);
        
sesfile.write(jsontext,false);

如果您无法找到数据目录,而只想从那里加载文件。(就我而言,它不存在于项目中,也不会使用网络预览编译创建)你可以先做这样的引导类型指令

var rdfile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'data.json');
var sesfile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'data2.json');
var jsontext = rdfile.read().toString();
var jsondoc = JSON.parse(jsontext);
sesfile.write(jsontext); 

希望它能帮助像我一样犯业余错误的人。