Flex 识别文本文件编码

代码
   
     
private function butClickHandle(e:MouseEvent): void
{
var file:File
= File.desktopDirectory;
// 打开文件
if (e.target.id == " but_openfile " ){
var txtfilter:FileFilter
= new FileFilter( " Text " , " *.as;*.css;*.txt;*.java;*.html;*.htm;*.xml " );
file.browseForOpen(
" Open " ,[txtfilter]);
file.addEventListener(Event.SELECT,function(e:Event):
void {
var file:File
= new File(e.target.nativePath);
var filestream:FileStream
= new FileStream;
filestream.open(file,FileMode.READ);
var bytes:ByteArray
= new ByteArray;
filestream.readBytes(bytes,
0 ,file.size);
txtfile.text
= transEncodingText(bytes);
});
}
// 打开文件夹
if (e.target.id == " but_opendir " ){
file.browseForDirectory(
" 打开文件夹 " );
file.addEventListener(Event.SELECT,function(e:Event):
void {
txtfile.text
= e.target.nativePath + File.lineEnding;
var contents:Array
= File(e.target).getDirectoryListing();
for (var i: int = 0 ;i < contents.length;i ++ ){
txtfile.text
+= contents[i].name + " \t " + contents[i].size + File.lineEnding;
}
});
}
}

// var bytes:ByteArray = new ByteArray;
// filestream.readBytes(bytes,0,file.size);
// 读取不同 编码的文档
private function transEncodingText(bytes:ByteArray):String
{
// 1. unicode 文档 开头 16进制码为 FF FE ,对应 十进制 数 为 255,254
if (bytes[ 0 ] == 255 && bytes[ 1 ] == 254 ){
return bytes.readMultiByte(bytes.length, " unicode " );
}
// 2.unicode big endian 开头 16进制 为 FE FF,对应十进制数 为 254,255
if (bytes[ 0 ] == 254 && bytes[ 1 ] == 255 ){
return bytes.readMultiByte(bytes.length, " UTF-16BE " );
}
// 3.utf-8 开头 16进制 为 EF BB ,对应 十进制 数 为 239,187
if (bytes[ 0 ] == 239 && bytes[ 1 ] == 187 ){
return bytes.readMultiByte(bytes.length, " utf-8 " );
}
// 默认采用系统编码 读取
return bytes.readMultiByte(bytes.length,File.systemCharset);
}

---------------------------------------------------------------

参考其他文章:了解字符的编码


你可能感兴趣的:(Flex)