我們都知道,檔案有不同的編碼,例如我們常用的中文編碼有:UTF8、GK2312 等,
Windows 作業系統中,新建的檔案會在起始部分加入幾個字符的前綴,來識別編碼,
例如,新建文本檔案,寫入單詞 Hello,另存為 UTF8,Hello 占 5 個位元組,但文本大小卻是 8 個位元組,(win7 系統下還是這樣的,win10 已經去掉了編碼前綴,所以 win10 下檔案大小依然是 5 個位元組,看來微軟自己也改變了,)
我們用 StreamWriter 來生成檔案,
using (StreamWriter sw = new StreamWriter("a.txt"))
{
sw.Write("Hello"); // 5 位元組
}
using (StreamWriter sw = new StreamWriter("b.txt", false, Encoding.UTF8))
{
sw.Write("Hello"); // 8 位元組
}
詭異的事情發生了,StreamWriter 的默認編碼是 UTF8,都是用的 UTF8 編碼,怎么檔案的大小會不一樣呢?
UTF8Encoding 有兩個私有屬性:emitUTF8Identifier 和 isThrowException,初始化時由建構式傳入,
emitUTF8Identifier表示是否添加編碼前綴isThrowException表示遇到編碼錯誤時是否報錯
由此可見,是否添加編碼前綴,是可以控制的,
Encoding 中 UTF8 定義如下,添加編碼前綴,
public static Encoding UTF8 {
get {
if (utf8Encoding == null) utf8Encoding = new UTF8Encoding(true);
return utf8Encoding;
}
}
而 StreamWriter 中使用的默認編碼,emitUTF8Identifier=false:
internal static Encoding UTF8NoBOM {
get {
if (_UTF8NoBOM == null) {
UTF8Encoding noBOM = new UTF8Encoding(false, true);
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
這就是開頭的代碼中兩個檔案大小不一樣的原因了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/62033.html
標籤:其他
