该闪就闪
-=本人学习flash过程中做的一些实验品=-

乱码解决方法 - 根据编码类型解析文本(AS3)

   Flash习作2009-4-14 11:15

package {
 import flash.text.TextField; 
 import flash.utils.ByteArray; 
 import flash.events.MouseEvent; 
 import flash.events.Event; 
 import flash.net.FileReference; 
 import flash.display.MovieClip;

 /**
  * @author jh7086
  */
 public class Test extends MovieClip {
  private var ref : FileReference;
  private var btn_browse : MovieClip;
  private var textField : TextField;

  public function Test() {
   ref = new FileReference();
   ref.addEventListener(Event.SELECT, file_select);
   ref.addEventListener(Event.COMPLETE, file_complete);
   
   btn_browse = this["_btn_browse"] as MovieClip;
   btn_browse.buttonMode = true;
   btn_browse.addEventListener(MouseEvent.CLICK, btn_browse_click);
   
   textField = this["_text"] as TextField;
  }

  private function btn_browse_click(event : MouseEvent) : void {
   ref.browse();
  }

  private function file_select(event : Event) : void {
   ref.load();
  }

  private function file_complete(event : Event) : void {
   //解析字节数组
   var data : ByteArray = ref.data;
   var type : String = getFileType(data);
   var length : uint = data.length;
   var result : String = "";
   switch(type) {
    case "ANSI" :
     data.position = 0;
     result = data.readMultiByte(length-data.position, "gb2312");
     break;
    case "Unicode" :
    case "Unicode big endian" :
    case "UTF-8" :
     result=data.toString();
     break;
   }
   textField.text = type + "\n\n" + result;
   textField.scrollV=1;
  }

  //根据文件头信息判断文本文件编码类型;
  private function getFileType(fileData : ByteArray) : String {
   var b0 : int = fileData.readUnsignedByte();
   var b1 : int = fileData.readUnsignedByte();
   var fileType : String = "ANSI";
   if(b0 == 0xFF && b1 == 0xFE) {
    fileType = "Unicode";
   }else if(b0 == 0xFE && b1 == 0xFF) {
    fileType = "Unicode big endian";
   }else if(b0 == 0xEF && b1 == 0xBB) {
    fileType = "UTF-8";
   }
   return fileType;
  }
 }
}

标签集:TAGS:flash AS3
回复Comments()点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}
我的日历
分类日志
友情链接
最新评论
搜索日志
访问计数
获取 RSS
我的 Blog:
jh7086 最新的 20 条日志
[Flash习作]
[Flash进修]
[Flash推荐]
[Flash涂鸦]
[听~音乐]
[我滴地盘er]
全站 Blog:
全站最新的 20 条日志
Powered by 5DBlog.com