[转载] Flex识别文本文件编码

1 private function butClickHandle(e:MouseEvent):void
2 {
3 var file:File = File.desktopDirectory;
4 //打开文件
5   if (e.target.id=="but_openfile"){
6 var txtfilter:FileFilter = new FileFilter("Text","*.as;*.css;*.txt;*.java;*.html;*.htm;*.xml");
7 file.browseForOpen("Open",[txtfilter]);
8 file.addEventListener(Event.SELECT,function(e:Event):void{
9 var file:File = new File(e.target.nativePath);
10 var filestream:FileStream = new FileStream;
11 filestream.open(file,FileMode.READ);
12 var bytes:ByteArray = new ByteArray;
13 filestream.readBytes(bytes,0,file.size);
14 txtfile.text = transEncodingText(bytes);
15 });
16 }
17 //打开文件夹
18 if (e.target.id=="but_opendir"){
19 file.browseForDirectory("打开文件夹");
20 file.addEventListener(Event.SELECT,function(e:Event):void{
21 txtfile.text = e.target.nativePath + File.lineEnding;
22 var contents:Array = File(e.target).getDirectoryListing();
23 for (var i:int=0;i<contents.length;i++){
24 txtfile.text += contents[i].name +"\t"+ contents[i].size + File.lineEnding;
25 }
26 });
27 }
28 }
29
30 //var bytes:ByteArray = new ByteArray;
31 //filestream.readBytes(bytes,0,file.size);
32 // 读取不同 编码的文档
33 private function transEncodingText(bytes:ByteArray):String
34 {
35 // 1. unicode 文档 开头 16进制码为 FF FE ,对应 十进制 数 为 255,254
36 if (bytes[0]==255 && bytes[1]==254){
37 return bytes.readMultiByte(bytes.length,"unicode");
38 }
39 // 2.unicode big endian 开头 16进制 为 FE FF,对应十进制数 为 254,255
40 if (bytes[0]==254 && bytes[1]==255){
41 return bytes.readMultiByte(bytes.length,"UTF-16BE");
42 }
43 // 3.utf-8 开头 16进制 为 EF BB ,对应 十进制 数 为 239,187
44 if (bytes[0]==239 && bytes[1]==187){
45 return bytes.readMultiByte(bytes.length,"utf-8");
46 }
47 // 默认采用系统编码 读取
48 return bytes.readMultiByte(bytes.length,File.systemCharset);
49 }
50
51
原文地址:https://www.cnblogs.com/liongis/p/1793324.html