我正在实现一些由文件支持的数据结构,并使用随机读写访问来更新结构。
并且偶然发现了一个坏错误或我的代码不正确。
经过数小时的检查和调试,它归结为以下片段,它隔离了错误?行为。
在循环内部,我应该在位置 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);
请,如果有人对此进行测试并得出与我相同的结论,即这是一个错误,请在 adobe 的错误库中对此错误进行投票,以便他们考虑修复它。
否则,如果有人能告诉我我做错了什么,我将不胜感激。
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);