AS3:从AS3中的文本文件中删除行

时间:2013-05-30 00:38:08

标签: actionscript-3 text-files filestream

我需要删除文本文件的最后3行,或者使用ActionScript 3.0重写最后3行

我理解如何附加文件,但我对如何使用文件流计数行感到迷茫。

2 个答案:

答案 0 :(得分:1)

试试这个,

var loader:URLLoader = new URLLoader(); //Creating a loader object
var myArray : Array;
loader.addEventListener(Event.COMPLETE, onLoaded); //On complete event handler

function onLoaded(e:Event):void {
   var myArray:Array = e.target.data.split(/\n/);
   //once you have all the lines as elements of the array you can change them
   myArray[myArray.length -1] = "ABC";
   myArray[myArray.length -2] = "DEF";
   myArray[myArray.length -3] = "GHI";
}

loader.load(new URLRequest("myFile.txt"));

//Then write out the contents of the array,

var f:File=new File("path\to\file.txt");
var handle:FileStream=new FileStream();
handle.open(f, FileMode.WRITE);
handle.writeUTFBytes(myArray);
handle.close();

答案 1 :(得分:1)

或尝试:

private function trimTextFile(txtFile:File, trimNum:uint):Boolean{
    if(txtFile.exists){
        var stream:FileStream = new FileStream();
        stream.open(txtFile, FileMode.READ);
        var tmp:Array = stream.readUTFBytes(stream.bytesAvailable).split("\n");
        stream.close();

        stream.open(txtFile, FileMode.WRITE);
        for(var i:uint = 0; i < tmp.length - trimNum; i++){
            stream.writeUTFBytes(tmp[i] +"\n");
        }
        stream.close();
        return true;
    }else{
        return false;
    }

}

并像这样称呼它

this.trimTextFile(File.desktopDirectory.resolvePath("test.txt"), 3);