zoukankan      html  css  js  c++  java
  • 初识IO流——二进制文件的读和写操作

      C#中,二进制文件的写和读操作分别由BinaryWrite类和BinaryReader类实现,它们都所属与System.IO命名空间。

      BinaryWriter类以二进制的形式将基元写入流,并支持用特定的编码写入字符串。

      BinaryReader类用特定的编码将基元数据类型读作二进制值。

      根据BinaryWriter类和BinaryReader类的实现写和读过程,其实可以将二者理解为一个"互逆"的过程。

      示例:分别用BinaryWrite类和BinaryReader类实现二进制文件的写操作和读操作。

      (1)BinaryWrite类实现写入操作:

     1 public void DoWrite(string str)
     2         {
     3             /*文件在项目中的相对于根目录的位置*/
     4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
     5 
     6             /*获取项目的根目录*/
     7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
     8 
     9             FileStream filestream = new FileStream(Full_path, FileMode.Append, FileAccess.Write);
    10 
    11             using (BinaryWriter writer = new BinaryWriter(filestream))
    12             {
    13 
    14                 writer.Write(str);
    15 
    16             }
    17 
    18         }

      (2)BinaryReader类实现文件的读取操作:

     1 public string DoRead()
     2         {
     3             /*文件在项目中的相对于根目录的位置*/
     4             string Relative_path = "/Binary/first_" + DateTime.Today.ToString("yy-MM-dd") + ".dat";
     5 
     6             /*获取项目的根目录*/
     7             string Full_path = AppDomain.CurrentDomain.BaseDirectory + Relative_path;
     8 
     9             /*存储结果*/
    10             string Read_text = string.Empty;
    11 
    12             FileStream filestream = new FileStream(Full_path, FileMode.Open, FileAccess.Read);
    13 
    14             using (BinaryReader reader = new BinaryReader(filestream))
    15             {
    16 
    17                 /*判断是否读到结尾处*/
    18                 while (reader.PeekChar() != -1)
    19                 {
    20 
    21                     Read_text += reader.ReadString();
    22 
    23                 }
    24 
    25                 return Read_text;
    26             }
    27 
    28         }

       

  • 相关阅读:
    读《高效能人士的七个习惯》有感
    Springboot中的日志
    fastjson JSON.toJavaObject() 实体类首字母大写属性无法解析问题
    java多线程编程实例
    IDEA插件配置推荐
    Spring Boot 自定义数据源 DruidDataSource
    zookeeper环境搭建
    eureka注册中心的使用
    记事本编码
    Chrome浏览器基本操作
  • 原文地址:https://www.cnblogs.com/SunshineAgain/p/5703480.html
Copyright © 2011-2022 走看看