C# 中的Stream流


流就是一個類的對象,很多文件的輸入輸出操作都以類的成員函數的方式來提供;

流其實是一種信息的轉換,是有序的,有輸入和輸出流(IO);

1.FileStream

文件流,讀取和保存文件操作使用;

//寫入
FileStream fs = new FileStream("data.txt", FileMode.OpenOrCreate);
string msg = "littlePerilla";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(msg);
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();

//讀取
FileStream fs = new FileStream("data.txt", FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, bytes.Length);
char[] c = Encoding.UTF8.GetChars(bytes);
fs.Flush();
fs.Close();

2.StreamReader 和 StreamWriter

粒度為字符的流;

void StreamWrite()
{
	string path = "test.txt";
	//創建StreamWriter 類的實例
	StreamWriter streamWriter = new StreamWriter(path);
	streamWriter.WriteLine("Perilla");
	streamWriter.WriteLine("13112345678");
	//刷新緩存
	streamWriter.Flush();
	//關閉流
	streamWriter.Close();
}

void StreamReader()
{
	//定義文件路徑
	string path = "test.txt";
	//創建 StreamReader 類的實例
	StreamReader streamReader = new StreamReader(path);
	//判斷文件中是否有字符
	while (streamReader.Peek() != -1)
	{
		//讀取文件中的一行字符
		string str = streamReader.ReadLine();
		Debug.Log(str);
	}
	streamReader.Close();
}

3.BinaryWriter 和 BinaryReader

粒度為字節的讀寫流;

// 讀取文件
void ReadFile()          
{
	FileStream fs = new FileStream("data.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("data.txt", FileMode.OpenOrCreate);
	BinaryWriter w = new BinaryWriter(fs);

	//以二進制方式向創建的文件中寫入內容 
	w.Write(1123);                
	w.Write(0.3135f);             
	w.Write(0.3188946);           
	w.Write(true);                
	w.Write("LittlePerilla");     

	w.Close();
	fs.Close();
}

4.MemoryStream

內存的讀寫流,字節粒度,支持Position和Seek操作,自由度更高;

支持異步讀寫,不需要手動釋放和開辟內存;

支持在任意位置修改操作;

class Program
{
    static void Main(string[] args)
    {
        string strValue = "LittlePerillaIsSuperHero";
        MemoryStream ms = new MemoryStream();
        ms.Write(Encoding.UTF8.GetBytes(strValue), 0, strValue.Length);

        Console.WriteLine(ms.Position);
        //打印測試
        byte[] byte1 = ms.GetBuffer();          
        string str1 = Encoding.UTF8.GetString(byte1);
        Console.WriteLine(str1);


        ms.Seek(2, SeekOrigin.Current);
        ms.ReadByte();
        ms.ReadByte();
        ms.ReadByte();
        ms.ReadByte();                    
        byte[] bytes3 = ms.ToArray();
        foreach (byte b in bytes3)
        {
            Console.Write(b + "-");
        }
        str1 = Encoding.UTF8.GetString(bytes3);
        Console.WriteLine("\n"+str1);
        //這里說明ms.ReadByte不會截斷讀完的數據

        MemoryStream ms2 = new MemoryStream();
        byte[] bytes6 = Encoding.UTF8.GetBytes("abcde");
        ms2.Write(bytes6, 0, bytes6.Length);
        Console.WriteLine(ms2.Position);
		
        //等價
        ms2.Position = 0;//ms2.Seek(0, SeekOrigin.Begin);  

        byte[] byteArray = new byte[5] { 110, 110, 110, 110, 110 };
        ms2.Read(byteArray, 2, 1);
        Console.WriteLine(Encoding.UTF8.GetString(byteArray));
        //結果為nnann,說明講ms2中的數據讀進byteArray中偏移2的位置,且只讀取1個字節;

        //指定位置寫入
        MemoryStream ms3 = new MemoryStream();
        byte[] bytesArr = Encoding.ASCII.GetBytes("abcdefg");
        ms3.Write(bytesArr, 0, bytesArr.Length);
        ms3.Position = 2;
        ms3.WriteByte(97);  //97代表的是a   這段代碼的意思是,將原先第二個的c替換為a
        string str = Encoding.ASCII.GetString(ms3.ToArray());
        Console.WriteLine(str); //輸出 abacdefg

        Console.ReadKey();
    }

}

5.NetworkStream

為網絡訪問提供數據的基礎流;用於 Stream 在阻止模式下通過套接字發送和接收數據的方法;

可以將類用於 NetworkStream 同步和異步數據傳輸;

創建NetworkStream必須提供Socket

詳細不適合在這里討論;待完善吧;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM