zoukankan      html  css  js  c++  java
  • C#文件流的读写

    1.文件流写入的一般步骤

      1.定义一个写文件流

      2.定义一个要写入的字符串

      3.完成字符串转byte数组

      4.把字节数组写入指定路径的文件

      5.关闭文件流

    2.文件流读入的一般步骤

      1.定义一个读文件流

      2.开辟一块足够大的字节数组内存空间

      3.把指定文件的内容读入字节数组

      4.完成字节数组转字符串操作

      5.关闭文件流

    具体代码如下:

     1 using System;
     2 using System.IO;
     3 using System.Text;
     4 namespace LearnFileStream
     5 {
     6     class Program
     7     {
     8         string path = @"E:AdvanceCSharpProjectLearnCSharpLearnFileStream.txt";
     9 
    10         private void TestWrite()
    11         {
    12             //定义写文件流
    13             FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
    14             //写入的内容
    15             string inputStr = "Learn Advanced C Sharp";
    16             //字符串转byte[]
    17             byte[] writeBytes = Encoding.UTF8.GetBytes(inputStr);
    18             //写入
    19             fsw.Write(writeBytes, 0, writeBytes.Length);
    20             //关闭文件流
    21             fsw.Close();
    22         }
    23 
    24         private void TestRead()
    25         {
    26             //定义读文件流
    27             FileStream fsr = new FileStream(path, FileMode.Open);
    28             //开辟内存区域 1024 * 1024 bytes
    29             byte[] readBytes = new byte[1024 * 1024];
    30             //开始读数据
    31            int count = fsr.Read(readBytes, 0, readBytes.Length);
    32             //byte[]转字符串
    33             string readStr = Encoding.UTF8.GetString(readBytes, 0, count);
    34             //关闭文件流
    35             fsr.Close();
    36             //显示文件内容
    37             Console.WriteLine(readStr);
    38         }
    39         static void Main(string[] args)
    40         {
    41             new Program().TestWrite();
    42             new Program().TestRead();
    43         }
    44     }
    45 }
  • 相关阅读:
    【第4题】 什么是https
    【第3题】 两个队列生成一个栈
    【第2题】 链表的逆置
    【第1题】 Pythonn内存管理以及垃圾回收机制
    tmunx error:invalid option: status-utf8 invalid option: utf8
    ubuntu install google-chrome-stable
    使用pyenv安装多个Python版本
    Linux命令行烧录树莓派镜像至SD卡
    freenode configuration sasl authentication in weechat
    尝试IRC & freenode
  • 原文地址:https://www.cnblogs.com/blackteeth/p/10204877.html
Copyright © 2011-2022 走看看