Skip to content

Instantly share code, notes, and snippets.

@billdawson
Created May 2, 2011 11:14
Show Gist options
  • Save billdawson/951461 to your computer and use it in GitHub Desktop.
Save billdawson/951461 to your computer and use it in GitHub Desktop.
Examples - Stream blog post - BufferStream
// Create the buffer & stream
var paragraph = Titanium.createBuffer({length: 1024});
var stream = Titanium.Stream.createStream({
mode: Titanium.Stream.MODE_WRITE, // There is also MODE_APPEND for writing
source: paragraph
});
// Write to stream in chunks, filling up "paragraph" buffer.
// Each chunk will be an encoded UTF-8 string because we
// don't specify otherwise.
var length = 0;
length += stream.write(Titanium.createBuffer({
value: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}));
length += stream.write(Titanium.createBuffer({
value: "Morbi vel mi in nunc bibendum congue at a ligula. Nunc at mauris dui, ac posuere ligula. "
}));
length += stream.write(Titanium.createBuffer({
value: " Curabitur posuere cursus orci, id convallis metus venenatis sed."
}));
// Close the stream. The buffer still has the data in it.
stream.close();
// Set the buffer length to the actual bytes written.
paragraph.length = length;
// Read back the buffer in chunks.
// Create the read stream & buffer.
var CHUNK_SIZE = 10;
var read_buffer = Titanium.createBuffer({length: 1024});
stream = Titanium.Stream.createStream({
mode: Titanium.Stream.MODE_READ,
source: paragraph
});
// Read until end.
length = 0;
var bytes_read = 0;
while ((length = stream.read(read_buffer, bytes_read, CHUNK_SIZE)) > 0) {
bytes_read += length;
};
// Get the read_buffer contents into a string.
var lorem = Ti.Codec.decodeString({
source: read_buffer,
charset: Ti.Codec.CHARSET_UTF8,
length: bytes_read,
position: 0
});
// Cleanup
stream.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment