Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

crash on File.read()

When I try doing:

var dir = Titanium.Filesystem.getApplicationDataDirectory();
var file = Titanium.Filesystem.getFile(settingsdir, 'settings.txt');
var settings = file.read();

Ignoring the .exists() error checking, if the file does exist but is 0 bytes, Titanium crashes on the .read() call. As soon as I make it 1 byte big it works fine.

— asked May 5th 2010 by David Barr
  • bug
0 Comments

1 Answer

  • Same here with 1.1.0. Before to even create the Filestream to read it, we do better by checking the file size first.

    Here is the code I use, hope it helps:

    var fl = Ti.Filesystem.getFile('file.txt'),
     fs = false,
     ret = false;
    
    if (fl.size() && (fs = fl.open(Ti.Filesystem.MODE_READ))) {
        ret = fs.read();
    
        if (ret && ret.length)
            ret = ret.toString();
    
        fs.close();
    }
    
    return ret;
    
    — answered June 30th 2011 by Allan Brazute
    permalink
    1 Comment
      • Updated code. I forgot to check if it exists first, because if not, the size() rise a exception saying the file does not exist. Annoying!
      var fl = Ti.Filesystem.getFile('file.txt'),
       fs = false,
       ret = false;
      
      if (fl.exists() && fl.size() && (fs = fl.open(Ti.Filesystem.MODE_READ))) {
          ret = fs.read();
      
          if (ret && ret.length)
              ret = ret.toString();
      
          fs.close();
      }
      
      return ret;
      

      — commented June 30th 2011 by Allan Brazute
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.