读写Unicode字符串(UTF8,UTF16…)

本文探讨了在文件操作中使用UTF-16与UTF-8编码的不同之处,包括编码原理、存储大小、读取方式以及转换过程中的注意事项。

写UTF-16字符串:

 

     class TestDataGenerator 
    { 
         public  static  void CreateNewTestDataFile( string FileName,  int record_length) 
        { 
             using (FileStream fs = File.Create(FileName)) 
            { 
                StringBuilder sb =  new StringBuilder(); 
                 for ( int i =  0; i < record_length; i++) 
                { 
                    sb.Append( ' '); 
                } 
                 byte[] content =  Encoding.Unicode.GetBytes(sb.ToString()); 
                fs.Write(content,  0, content.Length); 
            } 
        } 
    }

 

高亮的那句话用于把string编码为UTF-16字节流。

 

调用该函数生成包含100个字符的测试文件:

 
 

 

 

可以看到文件大小为200字节。原因是UTF-16使用2个字节来存储包括汉字在内的非ASCII字符

image

 

读取Unicode字符串:

 

            FileStream fs =  new System.IO.FileStream( " test.txt ", FileMode.Open, FileAccess.Read);
             byte[] blob =  new  byte[ 100];
            fs.Read(blob,  0100);
            fs.Flush();
             string strUtf16 = Encoding.Unicode.GetString(blob);
             string strUtf8 = Encoding.UTF8.GetString(blob);

 

从Watch窗口可见, 将字符串强转为UTF-8形式会出现乱码,这是因为UTF-8标准使用3个字节来存储汉字等字符,而不是UTF-16的2个字节。

image

 

 

尝试使用UTF-8编码存储字符: 

             byte[] content = Encoding.UTF8.GetBytes(sb.ToString()); 
            fs.Write(content,  0, content.Length);

 

 

刷新后查看文件属性可见文件大小变为300字节:

image

 

 

同理,读取时将UTF-8字符强转为UTF-16也是不行的, strUtf16显示为乱码:

image

 

转载于:https://www.cnblogs.com/k330/archive/2012/04/17/2453336.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值