My Mistake With readBytes in AIR

I was trying to read a specific part of a file in AIR. I thought readBytes function in FileStream can serve the purpose but I was wrong.

public function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void

Reads the number of data bytes, specified by the length parameter, from the file stream, byte stream, or byte array. The bytes are read into the ByteArray objected specified by the bytes parameter, starting at the position specified by offset.

The offset parameter is defined as the offset position in bytes. It defines where to store the data in bytes not where FileStream starts to read. The correct way is to move the FileStream.position and specify the length fo data needed.

  1. Ravi

    Thanks for the blog this helped me a lot…

  2. alex

    Hi there, ive been having a similar problem:

    filestream.writeBytes(byteArray, 0 , byteArray.length).

    I have been wanting to write the Bytes from say 18000 bytes to the byteArray.length (which is 20000 bytes). Is there a way to do this? i have trieds setting the offset to 18000, but it always returns the index out of range, and what you have outlined above seems to be the same problem.

    var f : File = File.desktopDirectory.resolvePath(”stream.mp3″);
    var fs : FileStream = new FileStream();
    fs.openAsync(f, FileMode.WRITE);
    var bArray : ByteArray = new ByteArray();
    stream.readBytes(bArray);
    fs.writeBytes(_newerBArray, 0, _newerBArray.length);

    so i would need to set the fs.position to a position in the bytearray? sorry about all the questions, it just seems no one else has documented this and its driving me a bit mad!

    thanks

  3. alex

    sorry, the last line of that code should have read
    fs.writeBytes(bArray, 0, bArray.length).

Leave a Reply

For spam filtering purposes, please copy the number 5453 to the field below: