我正在实现一些文件支持的数据结构,并使用随机读取和写入访问来更新结构。flash.filesystem.FileStream或Developer Error中的数据损坏问题?
并偶然发现一个错误的bug或我的代码是不正确的。
经过几个小时的检查和调试,它归结为下面的代码片段,它隔离了错误的?行为。
在循环内部,我认为是写入,读取和覆盖位置0处的字节。 在代码运行后,您会期望得到包含1个字节0x39
的文件。 而是文件增长,书写不发生在位置0,但在EOF。多次运行代码将导致文件越来越大。
如果您对线条fs.readByte();
发表评论,则代码的行为与预期相同。
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
var tf:File=File.userDirectory.resolvePath("test.txt");
var fs:FileStream=new FileStream();
fs.open(tf,FileMode.UPDATE);
for (var i=0;i<10;i++){
fs.position=0;
fs.writeByte(0x30+i);
fs.position=0;
fs.readByte(); //if you comment this line out, results are as expected
}
fs.close();
trace(tf.size);
请,如果有人正在测试这一点,并得出相同的结论作为我来说,这是 一个bug,请投在Adobe的bugbase这个bug,所以他们希望考虑将其固定。
否则,如果有人能告诉我我做错了什么,我将不胜感激。
TX利奥
编辑:澄清
//Alright, since the loop example caused some confusion about whether or not
//there would be use for such code I'll try with another snippet, that is hopefully
//closer to some real application.
//
//The code updates some bytes in the file
//and afterwards reads some bytes somewhere else in the file, eg. a header field.
//This time not in a loop but triggered by a timer, which could of course also
//be some event handler.
//
//I hope this makes the problem more apparent
import flash.utils.ByteArray;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.filesystem.FileMode;
var tf=File.userDirectory.resolvePath("test.txt");
var fs:FileStream=new FileStream();
var timerID:int;
var count:int=0;
var fileAction:Function=function(){
var dataToWrite:ByteArray=new ByteArray();
var dataToRead:ByteArray=new ByteArray();
dataToWrite[0]=0x31;
dataToWrite[1]=0x32;
fs.position=2;
fs.writeBytes(dataToWrite);
fs.position=0;
fs.readBytes(dataToRead,0,2); //this read will corrupt the previous write!!!
//instead updating two bytes at 0x02
//it will write to the end of file,
//appending two bytes
count++;
if (count>10) {
clearInterval(timerID);
fs.close();
trace("Excpected file size: 4")
trace("Actual size: "+tf.size);
}
}
fs.open(tf,FileMode.UPDATE);
fs.position=0;
fs.writeByte(0x30);
fs.writeByte(0x30);
timerID=setInterval(fileAction,100);
的代码片段没有做任何事情,除了这样做暴露这个错误,没有真正的用处。问题在于** READ打破了先前的WRITE **,这是一个严重的错误,并导致数据损坏。另外,如果您读取已写入的数据或任何其他数据,我认为这不重要。 – leostone 2013-02-10 09:44:44
请参阅原始问题中的编辑以获得更好的代码示例 – leostone 2013-02-10 12:39:54