0

Please advise on how to read text from a txt or csv file using Tide SDK. I already tried the following:

var f = Ti.Filesystem.getFile(Ti.Filesystem.getDesktopDirectory(),'file.txt');
var fs = Ti.Filesystem.getFileStream(f);
fs.open(Ti.Filesystem.MODE_READ);
contents = fs.read();

But it returns a file object, not text from the file.

terreb
  • 1,417
  • 2
  • 23
  • 40

3 Answers3

1

This could help you,

<script type="text/javascript">
//Get path for app executable
  var p = Ti.Filesystem.getApplicationDirectory().parent().parent();

//Get file
  var f = Ti.Filesystem.getFile(p, "readtest.txt");

//Open filestream
  var fs = Ti.Filesystem.getFileStream(f);
  fs.open(Ti.Filesystem.MODE_READ);

//Get contents of file
  var c = fs.read(f.size());

//Show contents
  alert(c);
</script>
ThatGuy343
  • 2,354
  • 3
  • 30
  • 55
  • What's the difference with what I posted above? Just different directory? Your code and mine return a file object. But the question is how to get text from txt files... – terreb Jun 27 '14 at 02:10
0

To get the text, use this:

var f = Ti.Filesystem.getFile(Ti.Filesystem.getDesktopDirectory(),'file.txt');
var content = f.read().text;

content is what you want.

Bowie
  • 992
  • 3
  • 10
  • 25
  • Hi, I've already tried this. I found that on Titanium Mobile docs, but it doesn't work for Tide SDK. f.read().text or fs.read(f.text) return undefined. – terreb Jun 27 '14 at 12:33
0

Ok, I found a solution. To get content of a file:

var f = Ti.Filesystem.getFile(Ti.Filesystem.getDesktopDirectory(),'yourfile.txt');
content = f.read().toString();

This does the trick and return a string of content.

terreb
  • 1,417
  • 2
  • 23
  • 40