views:

733

answers:

1

I'm trying to read an xml file into memory, add a node, then write over the original file.

The following code works just fine (it clears the file, then writes the new bytes over the top):

var stream:FileStream = new FileStream();
stream.open(file, FileMode.UPDATE);
stream.position = 0;
stream.truncate();
stream.writeUTFBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
stream.writeUTFBytes(File.lineEnding);
stream.writeUTFBytes(xml.toXMLString());
stream.close();

However, if I attempt to perform a read after the file has opened, the position / truncate calls don't work:

var stream:FileStream = new FileStream();
stream.open(file, FileMode.UPDATE);

var xml:XML = XML(stream.readUTFBytes(stream.bytesAvailable));

// Modify xml here

stream.position = 0;
stream.truncate();
stream.writeUTFBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
stream.writeUTFBytes(File.lineEnding);
stream.writeUTFBytes(xml.toXMLString());
stream.close();

Does anyone have any ideas why this doesn't work?

If you examine the stream, in the first code, after the call to truncate(), the bytesAvailable property will read 0. But in the second code, the bytesAvailable won't change (it will show the current file size).

+1  A: 

close the stream after the truncate() and then open it again. OR use openAsync instead.

stream.position = 0;
stream.truncate();
stream.close();
stream.open(file, FileMode.UPDATE);
stream.writeUTFBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
stream.writeUTFBytes(File.lineEnding);
stream.writeUTFBytes(xml.toXMLString());
stream.close();

OR

var stream:FileStream = new FileStream();
stream.openAsync(file, FileMode.UPDATE);
stream.position = 0;
stream.truncate();
stream.writeUTFBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
stream.writeUTFBytes(File.lineEnding);
stream.writeUTFBytes(xml.toXMLString());
stream.close();
kurt Mossman