黑马程序员—常见的几种Stream

来源:互联网 发布:域通电话 软件 编辑:程序博客网 时间:2024/06/06 01:08
---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------

 

1.   System.IO.FileStream: 对字节流进行操作

FileStream对象表示在磁盘或网络路径上指向文件的流,操作的是字节和字节数组。如果要操作byte数据时要用FileSteam。
string textContent = fileStream.ReadToEnd();
byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent);

//FileStream 读取 / 写入 文件
 public void FileStream_RW_File(string readPath,string writePath)
     {
         byte[] data = new byte[1024];
         int length = 0;
         try
         {
             FileStream readStream = new FileStream(readPath, FileMode.Open,FileAccess.Read);
             FileStream writeStream = new FileStream(writePath,FileMode.Create,FileAccess.Write);
             //文件指针指向0位置
             file.Seek(0, SeekOrigin.Begin);
             while((length = readStream.Read(data,0,data.Length))>0)
             {
                  writeStream.Write(data,0,length);
             }
            
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }


2.   System.IO.StreamReader  、 System.IO.StreamWriter:对字符流进行操作

继承自TextWriter类,操作的是字符数据。
如果你是准备读取byte数据的话,用StreamReader读取然后用 System.Text.Encoding.Default.GetBytes转化的话,则可能出现数据丢失
的情况,如byte数据的个数不对等。

//StreamReader读取文件  / StreamWriter写文件


public void readWriteFile()
        {
            string str = "";
            try
            {
                FileStream readStream = new FileStream("love.txt", FileMode.Open, FileAccess.Read);
                FileStream writeStream = new FileStream("love(副本).txt", FileMode.CreateNew,FileAccess.Write);
                StreamReader sr = new StreamReader(readStream, Encoding.Default);
                StreamWriter sw = new StreamWriter(writeStream, Encoding.GetEncoding("gb2312")); //输出文件的编码格式

                //while (sr.ReadLine()!=null)
                //{
                //   str += sr.ReadLine();
                //}
                str = sr.ReadToEnd();
                sw.Write(str);
               
                sr.Close();
                sw.Close();
            }
            catch (IOException ex)
            { }
        }

3.   System.IO.BinaryReader  、  System.IO.BinaryWriter:
用特定的编码将基元数据类型读作二进制值,可以对二进制直接进行操作。

private const string FILE_NAME = "Test.data";
    public static void Main(String[] args)
    {
        // Create the new, empty data file.
        if (File.Exists(FILE_NAME))
        {
            Console.WriteLine("{0} already exists!", FILE_NAME);
            return;
        }
        FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);
        // Write data to Test.data.
        for (int i = 0; i < 11; i++)
        {
            w.Write( (int) i);
        }
        w.Close();
        fs.Close();
        // Create the reader for data.
        fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
        BinaryReader r = new BinaryReader(fs);
        // Read data from Test.data.
        for (int i = 0; i < 11; i++)
        {
            Console.WriteLine(r.ReadInt32());
        }
        r.Close();
        fs.Close();
    }

  比如图片的存储,用string型的字符流无法操作的,还得用字节流。


4.   System.IO.MemoryStream来读写内存
创建支持存储区为内存的流。
内存流可降低应用程序中对临时缓冲区和临时文件的需要。直接操作的是内存。

MSDN例子:
 static void Main()
        {
            int count;
            byte[] byteArray;
            char[] charArray;
            UnicodeEncoding uniEncoding = new UnicodeEncoding();

            byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");//转换字符串为字节数据
            byte[] secondString = uniEncoding.GetBytes(Path.InvalidPathChars);

            using (MemoryStream memStream = new MemoryStream(100)) //申请Capacity为100的一块内存
            {
                //将firstString字节数据写到memStream内存流中
                memStream.Write(firstString, 0, firstString.Length);

                // Write the second string to the stream, byte by byte.
                count = 0;
                while (count < secondString.Length)
                {
                    memStream.WriteByte(secondString[count++]);  
                    //当写入的数据大于你刚开始申请的Capacity时,会自动增加容量(按一定规则),以保存所有数据。 
                }

                // Write the stream properties to the console.
                Console.WriteLine(
                    "Capacity = {0}, Length = {1}, Position = {2}\n",
                    memStream.Capacity.ToString(),
                    memStream.Length.ToString(),
                    memStream.Position.ToString());

                // Set the position to the beginning of the stream.
                memStream.Seek(0, SeekOrigin.Begin);

                // Read the first 20 bytes from the stream.
                byteArray = new byte[memStream.Length];
                count = memStream.Read(byteArray, 0, 20); //从内存流中直接读取字节数据,保存到byteArray字节数组中

                // Read the remaining bytes, byte by byte.
                while (count < memStream.Length)
                {
                    byteArray[count++] =
                        Convert.ToByte(memStream.ReadByte());
                }

               

                 // Decode the byte array into a char array
                // and write it to the console.

                charArray = new char[uniEncoding.GetCharCount( byteArray, 0, count)];
                uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);


                Console.WriteLine(charArray);
            }
        }


5.   System.IO.BufferedStream
缓冲区是内存中的字节块,使用缓冲区可进行读取或写入,但不能同时进行这两种操作。BufferedStream 的 Read 和 Write 方法自动维护缓冲区。

 

6.   System.Net.Sockets.NetworkStream 处理网络数据

 

 

---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------

详细请查看:http://net.itheima.com/

原创粉丝点击