How to append to a text file?

You must Login before you can answer or comment on any questions.

Is it possible to append to a text file instead of overwriting it on the Mobile platform? Filestreams aren't available for Mobile, and file writing seems to overwrite the entire file. This is what I've been trying so far:

var file = Titanium.Filesystem.getFile('someFile.txt');
 
file.write('First line\n');
 
/* After this line, contents of the file is 'Second Line'.
 * The first line is overwritten. */
file.write('Second line\n');
As basic as can be, but nothing else I've tried works, so I'm not sure what other options to add/try.

2 Answers

Accepted Answer

AFAIK, there currently is no append capability. So you need something like:

var file = Titanium.Filesystem.getFile('someFile.txt');
file.write(file.read() + 'First new line\n');
 
// Some time later in the code...
file.write(file.read() + 'Next new line\n');
Another option would be to read the file contents after the getFile() and store in a variable, then append to that variable and only write() once after you are all done appending data. What works best for a given scenario depends on your application design.

I wrote this to take a potentially large file and base64Encode it so it could be transferred using an XHR request. You could adjust it slightly to append a string to a text file, Doug Handy's solution is simple for small files but could cause a memory exception.

var instream = finalZip.open(Titanium.Filesystem.MODE_READ);
var outfile = Titanium.Filesystem.getFile(Ti.Filesystem.getExternalStorageDirectory()+'test.txt');
if(outfile.exists()){
        outfile.deleteFile();
}
var outstream = outfile.open(Titanium.Filesystem.MODE_WRITE);
var buffer = Titanium.createBuffer({length:1024});// Read and write chunks.
var size =0;
while((size = instream.read(buffer))]]>-1) {
    var str = Ti.Codec.decodeString({length:buffer.length, position:0, source:buffer});
    var encoded = Ti.Utils.base64encode(str);
    Ti.API.info('encoded.length:'+ encoded.length);
    var bufferNew = Titanium.createBuffer({length:encoded.length});
    var bytes = Ti.Codec.encodeString({source:encoded.text,dest:bufferNew});
    bufferNew.length = bytes;
 
    outstream.write(bufferNew);
    Titanium.API.info('Wrote '+ size +' bytes');
} // Cleanup.
instream.close();     
outstream.close()

Your Answer

Think you can help? Login to answer this question!