Flex - writeUTF() vs writeUTFBytes()
I am using FileStream.writeUTF() to write out an XML file, and I noticed that the file is being prefixed by strange characters, which is messing up my XML.
var file:File = File.desktopDirectory.resolvePath(FILENAME); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.WRITE); fileStream.writeUTF(data); // file now has data prefixed by strange characters fileStream.close();
It turns out that this is by design, as the writeUTF() function prefixes the file with the length of the file. God knows why it does that, but the solution is to use writeUTFBytes() instead - does the same thing without prefixing the data with the length. Does anyone know why the writeUTF() function writes out the length?

Yes I know. it allows for writing more stuff after the writeUTF. ex: if I want to write a “string1″ then a binary integer ‘1985′ I know when “string1″ ends and when the integer begins.
ex:
fileStream.writeUTF(”string1″);
fileStream.writeInt(1985);
results in (pseudo):
7string11985
so when parsing this I first do
var stringlength:int = fileStream.readInt();
then resd the string
var thestring:String = fileStream.readUTFBytes(stringlength);
//then I can read the number:
var thenumber:int = fileStream.readInt();
HTH/ Christoffer
Comment by Christoffer — January 11, 2009 @ 10:36 am
Ah you can use readUTF instead. just do this:
var thestring:String = fileStream.readUTF();
var thenumber:int = fileStream.readInt();
it reades the rength automatically
Comment by Christoffer — January 11, 2009 @ 10:43 am
Thanks, this has been bothering me for quite a while now and the solution is nice and simple!
Comment by chrillo.at — March 11, 2009 @ 2:53 pm