as3 ByteArray 之 readBytes

來源:互聯網
上載者:User

這個方法相當的神奇——

 

首先,readInt readUTF都是直接返回相應類型的資料,而這個方法卻要你傳入一個變數進去。

 

其次,這個方法很難從他的定義去理解,官方的文檔:

 

 public function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void語言版本: ActionScript 3.0運行時版本: AIR 1.0, Flash Player 9, Flash Lite 4從位元組流中讀取 length 參數指定的資料位元組數。從 offset 指定的位置開始,將位元組讀入 bytes 參數指定的 ByteArray 對象中,並將位元組寫入目標 ByteArray 中。 

“從位元組流中讀取 length 參數指定的資料位元組數。從 offset 指定的位置開始,將位元組讀入 bytes 參數指定的 ByteArray 對象中,並將位元組寫入目標 ByteArray 中。”

這個解釋有如下歧義:

1 有兩個位元組流:1調用此方法的位元組流,2傳入的第一個參數;究竟是從誰讀入誰?

按照通常的理解當然是調用方法的位元組流是來源——但事實卻不是。

2 offset是誰的offset,一般理解來是源位元組流的offset,——但事實卻也不是。

 

這兩個坑可是把我坑慘了,

 

正確的解釋應該是(源自好心網友):

上海|lite3(73548607*)  18:07:11byteArray.readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void從byteArray的byteArray.position開始,讀取length個位元組放到bytes裡,bytes從offset開始放.(bytes的position不變,bytesArray的position增加)byteArray.writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void從bytes的offset開始,讀取length個位元組放到byteArray裡,byteArray從byteArray.position開始放. (bytes的position不變, byteArray的position增加)總結: byteArray都是從byteArray.position開始(不論讀寫), bytes都是從offset開始(不論讀寫).http://www.litefeel.com/bytearray-api-explanation/看看API

 

附一段把一個長bytearray分段發送的代碼:

var tmp:ByteArray = new ByteArray();private function sendASection():void{if(d.bytesAvailable>0){try{tmp = new ByteArray ();tmp.clear();tmp.position = 0;var read_length = d.bytesAvailable>per?per:d.bytesAvailable;trace(read_total +","+  read_length);d.readBytes(tmp,  0, read_length);tmp.position = 0;read_total+=tmp.length;trace(   "progressHandler d.position:" + (d.position)+", current sent: "+tmp.bytesAvailable+"-"+    tmp.length+"/"+read_length+ ", left: "+ d.bytesAvailable +    ", total_length=" + total_length   );socket.writeBytes(tmp as ByteArray);socket.flush();if (this.uploadProgressHandler){//this.uploadProgressHandlertry{ExternalInterface.call(this.uploadProgressHandler, d.position, total_length);}catch(e){trace(e)}}//if(tmp.length<per) break;}catch(e){this.debug(e);//break;}}else trace("----------------------DONE ?--------------------------");}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.