• BinaryWriter和BinaryReader用法


     

      C#的FileStream类提供了最原始的字节级上的文件读写功能,但我们习惯于对字符串操作,于是StreamWriter和 StreamReader类增强了FileStream,它让我们在字符串级别上操作文件,但有的时候我们还是需要在字节级上操作文件,却又不是一个字节 一个字节的操作,通常是2个、4个或8个字节这样操作,这便有了BinaryWriter和BinaryReader类,它们可以将一个字符或数字按指定 个数字节写入,也可以一次读取指定个数字节转为字符或数字。

    下面看一个实例:

    BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是字符串。下面的代码示例演示如何向新的空文件流 (Test.data) 写入数据及从中读取数据。在当前目录中创建了数据文件之后,也就同时创建了相关的BinaryWriter 和 BinaryReaderBinaryWriter 用于向 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) 
        {
            // 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();
        }
    }
    复制代码

    有关该类的成员参见

    http://msdn.microsoft.com/zh-cn/library/system.io.binaryreader_members%28v=vs.80%29.aspx

  • 相关阅读:
    del:根据索引值删除元素
    Python insert()方法插入元素
    Python extend()方法添加元素
    Python append()方法添加元素
    Python list列表添加元素的3种方法
    什么是序列,Python序列详解(包括序列类型和常用操作)
    Python运算符优先级和结合性一览表
    Python print()函数高级用法
    Python input()函数:获取用户输入的字符串
    Python变量的定义和使用
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/5440490.html
Copyright © 2020-2023  润新知