天天看點

原 BinaryWriter和BinaryReader(二進制檔案的讀寫)

原文  BinaryWriter和BinaryReader(二進制檔案的讀寫)

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位地被編碼為整數

下面看一個執行個體:

BinaryWriter  和  BinaryReader  類用于讀取和寫入資料,而不是字元串。

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();  
    }  
          
}