流Stream

System.IO 提供了一个抽象类Stream , Stream类 支持对字节的读写操作。
所谓的“流”,指的是Stream,也就是所谓的一个文件区。

这个文件区中存储着的信息可以是在内存中,也可以是在硬盘中。流中的数据均以byte型数组去存储。

BufferedStream不是有缓冲区,而是本身就是缓冲区,可以用它来暂时存储其它流中的内容,然后flush进入相应的流。

至于StreamReader、StreamWriter、BinaryReader和BinaryWriter,他们都是流操作器,这些都是为了方便用户往流里写数据用的。
StreamReader是标准流读取器,StreamWriter是标准流写入器,BinaryReader是二进制流读取器,BinaryWriter是二进制流写入器。
标准流指的是文本文件,而二进制流指的就是二进制文件。

MemoryStream的构造函数完全可以什么都不填。当留空的时候则会产生一个空白的内存流,然后可以通过流操作器向里面写入数据。
总的来说MemoryStream还算是常用,不过得看你用来干什么。
如果只是单纯的文件操作,有用的只有FileStream。

流包含以下基本操作:
读操作(Reading)。读出流中的数据,把数据存放在另一种数据结构中,比如数组。
写操作(Writting)。即从另一种数据结构中读出数据,存放至流对象中。
搜索操作(Seeking)。即从流中的当前位置开始搜索,定位到指定的位置。
由于数据类型的不同,一些流可能不同时支持以上的所有操作。比如网络流就不支持搜索操作。Stream类提供了CanRead,CanWrite和CanSeek三种属
性,来表示流是否支持这些操作。

BinaryReader和BinaryWriter

BinaryReader和BinaryWriter这两个类提供了从字符串或原始数据到各种流之间的读写操作。

File和Directory

File类支持对文件的基本操作,包括创建、拷贝、移动、删除和打开一个文件。

Directory类则用于执行常见的各种目录操作,如创建、移动、浏览目录及其子目录。

File类和Directory类的基类都是抽象类FileSystemEntry。

TextReader和TextWriter

TextReader和TextWriter类都是抽象类。和Stream类的字节形式的输入和输出不同,它们用于Unicode字符的输入和输出。

StringReader和StringWriter

StringReader和StringWriter在字符串中读写字符。

StreamReader和StreamWriter

StreamReader和StreamWriter在流中读写字符。

BufferedStream

BufferedStream是为网络流添加缓冲的一种流类型,利用缓冲可以避免操作系统频繁地到磁盘上读取数据,从而减轻了操作系统的负担。

MemoryStream

MemoryStream是一个无缓冲流,它所封装的数据直接放在内存中,因此可以用于快速临时存储、进程间传递信息等。

NetworkSteam

Networksteam表示在互联网络上传递的流。

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace stream
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] buffer = null;

            string testString = "Stream!Hello World!";
            char[] ReadCharArray = null;
            byte[] ReadBuffer = null;
            string readString = string.Empty;


            using (MemoryStream stream = new MemoryStream())
            {
                Console.WriteLine("初始化字符串为:{0}", testString);

                if (stream.CanWrite)//如果该流可写
                {
                    //将testString写入流中

                    buffer = Encoding.Default.GetBytes(testString);//从该数组的第一个位置开始写,长度为3
                    stream.Write(buffer, 0, 3);
                    Console.WriteLine("现在Stream.Position在第{0}位置", stream.Position + 1);
                    Console.WriteLine("现在Stream的长度是{0}", stream.Length);

                    long newPositionStream = stream.CanSeek ? stream.Seek(3, SeekOrigin.Current) : 0;//从刚才结束的位置(当前位置)往后移3位,到第7位

                    Console.WriteLine("重新定位后Stream.Position再{0}位置", stream.Position + 1);
                    Console.WriteLine("现在Stream的长度是{0}", stream.Length);

                    if (newPositionStream < buffer.Length)
                    {
                        stream.Write(buffer, (int)newPositionStream, buffer.Length - (int)newPositionStream);//从新位置(第7位)一直写到buffer的末尾
                    }
                    stream.Position = 0;//写完后将stream的Position属性设置成0,开始读流中的数据

                    ReadBuffer = new byte[stream.Length];// 设置一个空的变量来接收流中的数据,长度根据stream的长度来决定

                    //设置stream总的读取数量 ,
                    //流已经把数据读到了readBuffer中
                    int Count = stream.CanRead ? stream.Read(ReadBuffer, 0, ReadBuffer.Length) : 0;

                    //通过流读出的readBuffer的数据求出从相应Char的数量
                    int charCount = Encoding.Default.GetCharCount(ReadBuffer, 0, Count);
                    //通过该Char的数量 设定一个新的readCharArray数组
                    ReadCharArray = new char[charCount];

                    Encoding.Default.GetDecoder().GetChars(ReadBuffer, 0, Count, ReadCharArray, 0);
                    for (int i = 0; i < ReadCharArray.Length; i++)
                    {
                        readString += ReadCharArray[i];
                    }
                    Console.WriteLine("读取字符串为:{0}", readString);

                }

                stream.Close();

            }
    Console.ReadLine();
}

举例:

(1)BinaryWriter 和 BinaryReader

BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是字符串。向新的空文件流 (Test.data) 写入数据及从中读取数据。在当前目录中创建了数据文件之后,也就同时创建了相关的 BinaryWriter 和 BinaryReader,BinaryWriter 用于向 Test.data 写入整数 0 到 10,Test.data 将文件指针置于文件尾。在将文件指针设置回初始位置后,BinaryReader 读出指定的内容。

using System;
using System.IO;
class MyStream 
{
    private const string FILE_NAME = "Test.data";
    public static void Main(String[] args) 
    {
        // 创建空白文件
        if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
        // 创建BinaryWriter实例 用于写文件
        BinaryWriter w = new BinaryWriter(fs);
        // 写文件
        for (int i = 0; i < 11; i++) 
        {
            w.Write( (int) i);
        }
        w.Close();
        fs.Close();
        // 创建BinaryReader实例用于读文件
        fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
        BinaryReader r = new BinaryReader(fs);
        // 读文件
        for (int i = 0; i < 11; i++) 
        {
            Console.WriteLine(r.ReadInt32());
        }
        r.Close();
        fs.Close();
    }
}
(2)从文件读文本
using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            // 创建StreamReader 实例读文件.
            
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                // 读文件到结尾并展示
                
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e) 
        {
            // 捕获异常
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

 

 









posted @ 2017-07-31 17:12  超级芒果  阅读(358)  评论(0编辑  收藏  举报