文件流

一.文件流的定义

fstream继承自iostream。与iostream、sstream共同作为头文件构成IO标准库。

二.所含类型

       fstream头文件定义了三种支持文件IO的类型:
  istringstream从文件中读取;由istream派生而来
  ostringstream写到文件中去;由ostream派生而来
  fstream读写文件;由iostream派生而来

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

  1.定义一个写文件流

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

  3.完成字符串转byte数组

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

  5.关闭文件流

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

  1.定义一个读文件流

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

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

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

  5.关闭文件流

五.实例代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    using System;
    using System.IO;
    using System.Text;
    namespace LearnFileStream
    {
        class Program
        {
            string path = @"E:\hhhh.txt";

            private void TestWrite()
            {
                //定义写文件流
                FileStream fsw = new FileStream(path, FileMode.OpenOrCreate);
                //写入的内容
                string inputStr = "Learn Advanced C Sharp";
                //字符串转byte[]
                byte[] writeBytes = Encoding.UTF8.GetBytes(inputStr);
                //写入
                fsw.Write(writeBytes, 0, writeBytes.Length);
                //关闭文件流
                fsw.Close();
            }

            private void TestRead()
            {
                //定义读文件流
                FileStream fsr = new FileStream(path, FileMode.Open);
                //开辟内存区域 1024 * 1024 bytes
                byte[] readBytes = new byte[1024 * 1024];
                //开始读数据
                int count = fsr.Read(readBytes, 0, readBytes.Length);
                //byte[]转字符串
                string readStr = Encoding.UTF8.GetString(readBytes, 0, count);
                //关闭文件流
                fsr.Close();
                //显示文件内容
                Console.WriteLine(readStr);
            }
            static void Main(string[] args)
            {
                new Program().TestWrite();
                new Program().TestRead();
            }
        }
    }
}

结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值