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

---------------------- 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/

黑马程序员是一家IT培训机构,提供各种技术培训课程,包括网络通信相关的课程。在网络通信中,socket是一种编程接口,用于实现不同主机之间的通信。通过socket函数创建一个套接字,指定域名、类型和协议。域名可以是AF_INET、AF_INET6或AF_UNIX,类型可以是SOCK_STREAM(用于TCP通信)或SOCK_DGRAM(用于UDP通信),协议可以是0表示自动选择适合的协议。创建成功后,套接字会返回一个文件描述符,用于在后续的通信中进行读写操作。 在TCP通信中,服务器和客户端的流程大致相同。服务器首先使用socket函数创建套接字,然后使用bind函数绑定服务器地址结构,接着使用listen函数设置监听上限。服务器通过accept函数阻塞监听客户端连接,并使用read函数读取客户端传来的数据,进行相应的处理后,使用write函数将处理后的数据写回给客户端,最后使用close函数关闭套接字。客户端也是先使用socket函数创建套接字,然后使用connect函数与服务器建立连接,之后使用write函数将数据写入套接字,再使用read函数读取服务器返回的数据,最后使用close函数关闭套接字。 在UDP通信中,服务器和客户端的流程也有所不同。服务器使用socket函数创建套接字,指定类型为SOCK_DGRAM,然后使用bind函数绑定服务器地址结构。服务器通过recvfrom函数接收客户端传来的数据,并进行相应的处理,最后使用sendto函数将处理后的数据发送回给客户端。客户端同样使用socket函数创建套接字,然后通过sendto函数将数据发送给服务器,再使用recvfrom函数接收服务器返回的数据。 总之,socket网络通信是通过创建套接字实现不同主机之间的通信。根据使用的协议不同,可以选择TCP或UDP通信方式。服务器和客户端根据流程进行相应的操作,实现数据的传输和交互。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值