ファイルに裏打ちされたデータ構造を実装し、ランダムな読み取りおよび書き込みアクセスを使用して構造を更新しました。
そして、悪いバグに遭遇したか、私のコードが正しくありません。
何時間ものチェックとデバッグの後、エラーを特定する次のスニペットに要約されましたか? 行動。
ループ内で、位置 0 のバイトを書き込み、読み取り、上書きしていると思われます。コードが実行された後、 1 byte を含むファイルになると予想されます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);