Cannot write to file in Titanium

2019-09-08 09:09发布

问题:

I am having trouble writing to a file in Titanium Studio. specifically .json file. Code is compiled through and no exception was thrown.

Here is my relevant section of code, I parse the file to var first before adding element and stringify it to be written back. Reading works perfectly, so is adding element, it's the writing process that has issues

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])

Note: I have consulted Documentation and done some of my own search, some are suggesting that "Filestream" should be used in place of normal file along with .close(), I have yet got them working but it could be pointers the solution, if anyone knows how to get it working

Thanks in advance.

EDIT: This question is flagged for duplication, initially I deemed that was 2 separate issues, one was about merely writing text to a file. Another is parsing event.media (picture) into a file.

回答1:

I got it working now, The issue was that I was trying to write to file in read-only directory

Ti.Filesystem.resourcesDirectory: A read-only directory where your application resources are located

Ti.Filesystem.applicationDataDirectory: A read/write directory accessible by your app. Place your application-specific files in this directory. The contents of this directory persist until you remove the files or until the user uninstalls the application

Here is my code, directory is modified

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);

If you are unable to locate data directory and simply want to load the file from there. (In my case it does not exist in project nor will be created with Webpreview compilings) You can do bootstrap-ish type instruction like this first

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); 

hope it helps whomever makes amateur mistake like I did.