zoukankan      html  css  js  c++  java
  • BinaryWriter 及BinaryReader 在二进制的读与写,做好笔记,以备忘。

                                                                                                                                                         

          

    BinaryWriter  BinaryReader 是一个二进制流管理对象,方便我们操作这些二进制数据,值得借鉴,相比我们自己去拼接与遍历要好的多。

        

    代码
    static void Main()
        {
            
    const int arrayLength = 1000;

            
    // Create random data to write to the stream.
            byte[] dataArray = new byte[arrayLength];
            
    new Random().NextBytes(dataArray);

            BinaryWriter binWriter 
    = new BinaryWriter(new MemoryStream());

            
    // Write the data to the stream.
            Console.WriteLine("Writing the data.");
            binWriter.Write(dataArray);

            
    // Create the reader using the stream from the writer.
            BinaryReader binReader = 
                
    new BinaryReader(binWriter.BaseStream);

            
    // Set Position to the beginning of the stream. //设置流开始的位置
            binReader.BaseStream.Position = 0;

            
    // Read and verify the data. 读取并验证数据,从二进制流中读取。  
            byte[] verifyArray = binReader.ReadBytes(arrayLength);  //从binReader对象当中读取指定长度数据 binReader对象已经被初始化。
            if(verifyArray.Length != arrayLength)
            {
                Console.WriteLine(
    "Error writing the data.");
                
    return;
            }
            
    for(int i = 0; i < arrayLength; i++)
            {
                
    if(verifyArray[i] != dataArray[i])
                {
                    Console.WriteLine(
    "Error writing the data.");
                    
    return;
                }
            }
            Console.WriteLine(
    "The data was written and verified.");
        }

  • 相关阅读:
    图,深度,广度优先遍历(一)
    java实现快速排序
    图,深度,广度优先遍历(二)
    图,深度,广度优先遍历(三)
    Jpa动态多表if多条件联合查询(if中包含list不为null和“=”的判断),并对查询结果进行分页
    SpringBoo启动报错:Failed to load property source from location ‘classpath:/bootstrap.yml‘
    Java对象创建和Javabean创建
    Linux解压命令
    BDD测试利器:mocha+should.js
    《老码识途》读书笔记:第一章(中)
  • 原文地址:https://www.cnblogs.com/chenli0513/p/1871136.html
Copyright © 2011-2022 走看看