BinaryWriter和BinaryReader(二進位制檔案的讀寫)
阿新 • • 發佈:2019-02-07
C#的FileStream類提供了最原始的位元組級上的檔案讀寫功能,但我們習慣於對字串操作,於是StreamWriter和 StreamReader類增強了FileStream,它讓我們在字串級別上操作檔案,但有的時候我們還是需要在位元組級上操作檔案,卻又不是一個位元組 一個位元組的操作,通常是2個、4個或8個位元組這樣操作,這便有了BinaryWriter和BinaryReader類,它們可以將一個字元或數字按指定 個數位元組寫入,也可以一次讀取指定個數位元組轉為字元或數字。
1.BinaryWriter類
BinaryWriter類以二進位制形式將基元型別寫入流,並支援用特定的編碼寫入字串。
常用的方法:
Close 關閉當前的BinaryWriter和基礎流
Seek 設定當前流中的位置
Write 將值寫入當前流
2.BinartReader類
BinartReader類用特定的編碼將基元資料型別讀作二進位制值。
常用的方法:
Close 關閉當前閱讀器及基礎流
Read 從基礎流中讀取字元,並提升流的當前位置
ReadBytes 從當前流將count個位元組讀入位元組陣列,並使當前位置提升count個位元組
ReadInt32 從當前流中讀取4個位元組有符號整數,並使流的當前位置提升4個位元組
ReadString 從當前流讀取一個字串。字串有長度字首,一次7位地被編碼為整數
下面看一個例項:
using UnityEngine; using System; using System.Text; using System.IO; using System.Collections; using System.Collections.Generic; public class FileOperator : MonoBehaviour { // Use this for initialization void Start () { WriteFile (); ReadFile(); } void ReadFile() // 讀取檔案 { FileStream fs = new FileStream ("D:\\MemoryStreamTest.txt", FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader (fs); //以二進位制方式讀取檔案中的內容 int i = r.ReadInt32 (); float f = r.ReadSingle (); double d = r.ReadDouble (); bool b = r.ReadBoolean (); string s = r.ReadString(); Debug.Log (i); Debug.Log (f); Debug.Log (d); Debug.Log (b); Debug.Log (s); r.Close (); fs.Close (); } void WriteFile() // 寫入檔案 { FileStream fs = new FileStream ("D:\\BinaryStreamTest.txt", FileMode.OpenOrCreate); BinaryWriter w = new BinaryWriter (fs); //以二進位制方式向建立的檔案中寫入內容 w.Write (666); // 整型 w.Write (66.6f); // 浮點型 w.Write (6.66); // double型 w.Write(true); // 布林型 w.Write ("六六六"); // 字串型 w.Close (); fs.Close(); } }