调用FileStream.readUTFBytes()后,FileStream.truncate()不起作用(Adobe AIR)

时间:2009-04-21 22:02:40

标签: xml flex adobe air filestream

我正在尝试将xml文件读入内存,添加节点,然后写入原始文件。

以下代码工作正常(它清除文件,然后将新字节写在顶部):

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();

但是,如果我在文件打开后尝试执行读取,则位置/截断调用不起作用:

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();

有没有人知道为什么这不起作用?

如果检查流,在第一个代码中,在调用truncate()之后,bytesAvailable属性将读为0.但在第二个代码中,bytesAvailable将不会更改(它将显示当前文件大小)

1 个答案:

答案 0 :(得分:1)

在truncate()之后关闭流,然后再次打开它。或者使用openAsync。

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();